Java中使用URL(Uniform Resource Locator)可以訪問不同協議的資源。常見的協議有HTTP、FTP、Telnet等,在這裡我們着重講解HTTP協議。
一、URL的構成
URL由三部分組成:協議、主機和路徑。例如:http://www.example.com/index.html。其中,http是協議,www.example.com是主機,index.html是路徑。除此之外,URL還可以有查詢參數和錨點。
下面我們通過代碼實現獲取URL的各個部分:
import java.net.URL; public class URLDemo { public static void main(String[] args) throws Exception { URL url = new URL("http://www.example.com/index.html?name=yiibai#example"); System.out.println("協議:" + url.getProtocol()); System.out.println("主機:" + url.getHost()); System.out.println("路徑:" + url.getPath()); System.out.println("查詢參數:" + url.getQuery()); System.out.println("錨點:" + url.getRef()); } }
二、URL的解析
在實際應用中,我們常常需要對URL進行解析,獲取其中的參數。URL的解析可以使用java.net.URLDecoder類。下面通過代碼演示解析URL:
import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; public class URLParser { public static Map parse(String url) throws Exception { Map params = new HashMap(); int index = url.indexOf('?'); if (index != -1) { String query = url.substring(index + 1); String[] pairs = query.split("&"); for (String pair : pairs) { int pos = pair.indexOf('='); if (pos != -1) { params.put(URLDecoder.decode(pair.substring(0, pos), "UTF-8"), URLDecoder.decode(pair.substring(pos + 1), "UTF-8")); } } } return params; } public static void main(String[] args) throws Exception { String url = "http://www.example.com/login?username=yiibai&password=123456"; Map params = URLParser.parse(url); System.out.println("用戶名:" + params.get("username")); System.out.println("密碼:" + params.get("password")); } }
三、URL的請求
使用Java可以方便地實現對URL的請求,可以使用HttpURLConnection類。下面通過代碼演示對URL進行GET請求:
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; public class HttpDemo { public static String getRequest(String urlString) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); InputStream is = conn.getInputStream(); Scanner scanner = new Scanner(is, "UTF-8"); StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { sb.append(scanner.nextLine()); } scanner.close(); conn.disconnect(); return sb.toString(); } public static void main(String[] args) throws IOException { String url = "http://www.example.com/index.html"; String content = getRequest(url); System.out.println(content); } }
如果需要發送POST請求,可以調用HttpURLConnection的setRequestMethod方法,並且需要設置Content-Type和Content-Length:
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class HttpDemo { public static String postRequest(String urlString, String body) throws IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", Integer.toString(body.getBytes(StandardCharsets.UTF_8).length)); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(body.getBytes(StandardCharsets.UTF_8)); os.close(); InputStream is = conn.getInputStream(); Scanner scanner = new Scanner(is, "UTF-8"); StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { sb.append(scanner.nextLine()); } scanner.close(); conn.disconnect(); return sb.toString(); } public static void main(String[] args) throws IOException { String url = "http://www.example.com/login"; String body = "username=yiibai&password=123456"; String content = postRequest(url, body); System.out.println(content); } }
四、URL的拼接
有時候我們需要動態生成URL,可以使用StringBuilder來拼接URL。下面通過代碼演示:
public class URLBuilder { public static String build(String baseUrl, Map params) { StringBuilder sb = new StringBuilder(); sb.append(baseUrl); sb.append('?'); for (Map.Entry entry : params.entrySet()) { sb.append(entry.getKey()); sb.append('='); sb.append(entry.getValue()); sb.append('&'); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static void main(String[] args) { String baseUrl = "http://www.example.com/search"; Map params = new HashMap(); params.put("q", "Java"); params.put("page", "1"); String url = URLBuilder.build(baseUrl, params); System.out.println(url); } }
五、URL的編碼
URL中的參數需要進行編碼,避免出現特殊字符。Java內置了URLEncoder和URLDecoder類,可以用於URL的編碼和解碼。下面通過代碼演示:
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; public class URLEncodeDemo { public static void main(String[] args) throws UnsupportedEncodingException { String url = "http://www.example.com/search?q=Java 編程"; String encodedUrl = URLEncoder.encode(url, "UTF-8"); System.out.println(encodedUrl); } }
需要注意的是,對於URL中的路徑部分,只需要對特殊字符進行編碼,而對於查詢參數部分,需要對整個參數字符串進行編碼。
原創文章,作者:LEEC,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/139721.html