In Java, you can encode and decode URLs using the java.net.URLEncoder and java.net.URLDecoder classes. These classes handle encoding and decoding in compliance with the application/x-www-form-urlencoded MIME type.
Here’s how you can encode and decode URLs:
Code Example
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.URLDecoder;
public class URLEncoderDecoderExample {
public static void main(String[] args) {
try {
// The String to be encoded
String url = "https://example.com/query?name=John Doe&age=25";
// Encoding URL
String encodedUrl = URLEncoder.encode(url, "UTF-8");
System.out.println("Encoded URL: " + encodedUrl);
// Decoding URL
String decodedUrl = URLDecoder.decode(encodedUrl, "UTF-8");
System.out.println("Decoded URL: " + decodedUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); // Handle exception if unsupported encoding is provided
}
}
}
Explanation:
- Encoding:
- The
URLEncoder.encode()method encodes special characters in the URL to make it safe for transmission over the network. - UTF-8 is typically used as the charset.
- The
- Decoding:
- The
URLDecoder.decode()method decodes the string back to its original format.
- The
Sample Output:
If the input is:
https://example.com/query?name=John Doe&age=25
After encoding:
https%3A%2F%2Fexample.com%2Fquery%3Fname%3DJohn+Doe%26age%3D25
After decoding:
https://example.com/query?name=John Doe&age=25
Notes:
- Replace spaces with
+in the encoded string. This is because spaces are not typically allowed in URLs, and encoding replaces them. - Use
"UTF-8"because it’s the most widely used and supports all Unicode characters.
