在Java中,可以使用java.net.URLEncoder
和java.net.URLDecoder
类对URL进行编码和解码。这两个类提供了将字符串转换为application/x-www-form-urlencoded MIME格式的方法。
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class URLEncodingExample {
public static void main(String[] args) {
String url = "https://example.com/search?q=你好世界";
try {
String encodedUrl = URLEncoder.encode(url, "UTF-8");
System.out.println("Encoded URL: " + encodedUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class URLDecodingExample {
public static void main(String[] args) {
String encodedUrl = "https%3A%2F%2Fexample.com%2Fsearch%3Fq%3D%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C";
try {
String decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
System.out.println("Decoded URL: " + decodedUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
注意:在使用URLEncoder.encode()
和URLDecoder.decode()
时,需要指定字符集(如"UTF-8")。这是因为URL编码和解码过程涉及到字符的编码和解码。