在Java中,URL编码主要用于将特殊字符转换为可在URL中传输的格式。以下是一些常用的URL编码技巧:
java.net.URLEncoder
类进行编码: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
类进行编码: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);
}
}
注意事项:
&
、=
、+
等,在URL编码中具有特殊含义,需要进行转义。