How do you use encodeURIComponent in Java?
Use the URLEncoder.encode() method in Java to perform URL encoding, which converts special characters in a string to URL encoding format. Below is an example code:
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class URLEncoderExample {
public static void main(String[] args) {
try {
String url = "https://www.example.com/?q=java编程";
String encodedUrl = URLEncoder.encode(url, "UTF-8");
System.out.println("Encoded URL: " + encodedUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
In the example above, we encoded a URL containing Chinese characters using the URLEncoder.encode() method. The output result is: https%3A%2F%2Fwww.example.com%2F%3Fq%3Djava%E7%BC%96%E7%A8%8B.