在Java中,java.net.URL类用于表示统一资源定位符。以下是一些使用URL类的技巧:
try {
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https://www.example.com/path?query=param#anchor");
String protocol = url.getProtocol(); // "https"
String host = url.getHost(); // "www.example.com"
int port = url.getPort(); // -1(如果未指定端口)
String path = url.getPath(); // "/path"
String query = url.getQuery(); // "query=param"
String ref = url.getRef(); // "anchor"
try {
URL url = new URL("https://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
}
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class URLEncodingExample {
public static void main(String[] args) {
try {
String text = "Hello, World!";
String encodedText = URLEncoder.encode(text, "UTF-8");
System.out.println(encodedText); // 输出:Hello%2C+World%21
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
public class QueryParameterParsingExample {
public static void main(String[] args) {
try {
URI uri = new URI("https://www.example.com/path?query=param&anotherParam=anotherValue");
String query = uri.getQuery();
Map<String, String> queryParams = new HashMap<>();
for (String param : query.split("&")) {
String[] keyValue = param.split("=");
if (keyValue.length == 2) {
queryParams.put(keyValue[0], keyValue[1]);
}
}
System.out.println(queryParams); // 输出:{query=param, anotherParam=anotherValue}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
这些技巧可以帮助您更好地使用Java中的URL类。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。