Reading:
Java Url Decode

Java Url Decode

Metamug
Java Url Decode

Encoded URL

Url decoding is used to decode the URI part of the URL, values of parameters are decoded for further use.

You would receive url-ended text typically from a http request, from the path parameter.

For example, the url would look like this.

String url = "http://www.metamug.com?key1=value+1&key2=value%40%21%242&key3=value%253";

You shouldn't pass the whole url into URLDecoder, instead pass the parameter value that needs to be decoded.

Fetch parameters from the url

    URI uri = new URI(testUrl);

    String scheme = uri.getScheme();
    String host = uri.getHost();
    String query = uri.getRawQuery();
public static Map<String, String> getQueryMap(String query) {  
    String[] params = query.split("&");  
    Map<String, String> map = new HashMap<String, String>();

    for (String param : params) {  
        String name = param.split("=")[0];  
        String value = param.split("=")[1];  
        map.put(name, value);  
    }  
    return map;  
}

Decode url using URLDecoder

try {
    String key2 = getQueryMap(query).get("key2");
    String result = java.net.URLDecoder.decode(key2, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
}

Java 10 added direct support for Charset to the API, meaning there's no need to catch UnsupportedEncodingException:

String result = java.net.URLDecoder.decode(url, StandardCharsets.UTF_8);

Note that a character encoding (such as UTF-8 or ASCII) is what determines the mapping of characters to raw bytes. For a good intro to character encodings, see this article.

URL Decoder in Apache Commons

If you are using older versions of java and have apache commons already loaded in your project, you can use URLCodec.

import org.apache.commons.codec.net.URLCodec;
//...
String decodedUrl = new URLCodec().decode(url);

The default charset is UTF-8



Icon For Arrow-up
Comments

Post a comment