In Java, you may encounter situations where URLs contain encoded special characters. These encoded characters use a specific format that prevents special characters, such as ":" and "/," from interfering with the URL interpretation. To decode these encoded characters and obtain the original URL, you need to utilize a specific decoding process.
Java provides a convenient class called URLDecoder that allows you to easily decode encoded URLs. Here's an example code that demonstrates how to use URLDecoder:
import java.net.URLDecoder; import java.nio.charset.StandardCharsets; // ... String encodedUrl = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type%3D%26type%3Dprivate"; try { String decodedUrl = URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8.name()); System.out.println("Decoded URL: " + decodedUrl); } catch (UnsupportedEncodingException e) { // not going to happen - value came from JDK's own StandardCharsets }
Starting with Java 10, the URLDecoder class supports direct specification of the Charset. As a result, you can simplify the code even further:
import java.net.URLDecoder; import java.nio.charset.StandardCharsets; // ... String encodedUrl = "https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type%3D%26type%3Dprivate"; String decodedUrl = URLDecoder.decode(encodedUrl, StandardCharsets.UTF_8); System.out.println("Decoded URL: " + decodedUrl);
Decoding encoded URLs in Java is straightforward using the URLDecoder class. By understanding the concept of URL encoding and leveraging the provided tools, you can easily convert encoded URLs to their original form, making it easier to work with URLs in your Java applications.
The above is the detailed content of How to Decode Encoded URLs in Java Using URLDecoder?. For more information, please follow other related articles on the PHP Chinese website!