在Java中,URL編碼主要用于將特殊字符轉(zhuǎn)換為可在URL中傳輸?shù)母袷?。以下是一些常用的URL編碼技巧:
java.net.URLEncoder
類(lèi)進(jìn)行編碼:import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class URLEncodingExample {
public static void main(String[] args) {
String url = "https://example.com/search?q=Java%20URL%20Encoding";
String encodedUrl = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
System.out.println("Encoded URL: " + encodedUrl);
}
}
java.net.URI
類(lèi)進(jìn)行編碼:import java.net.URI;
import java.net.URISyntaxException;
public class URLEncodingExample {
public static void main(String[] args) {
String url = "https://example.com/search?q=Java%20URL%20Encoding";
try {
URI encodedUri = new URI(url);
System.out.println("Encoded URI: " + encodedUri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class URLEncodingExample {
public static void main(String[] args) {
String query = "Java URL Encoding";
String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8.toString());
System.out.println("Encoded Query: " + encodedQuery);
}
}
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
public class URLDecodingExample {
public static void main(String[] args) {
String encodedUrl = "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3DJava%2520URL%2520Encoding";
String decodedUrl = URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8.toString());
System.out.println("Decoded URL: " + decodedUrl);
}
}
注意事項(xiàng):
&
、=
、+
等,在URL編碼中具有特殊含義,需要進(jìn)行轉(zhuǎn)義。