'decodeURI in java

I want to decode this uri in java:

URLDecoder.decode("/demo/%E4%B8%AD%E6%96%87/test%3Fa%3Da", UtilConst.UTF8);
// return "/demo/中文/test?a=a"

This is not my expected result, since it change the uri structure。I want to get the same result like JavaScript encodeURI method:

decodeURI('/demo/%E4%B8%AD%E6%96%87/test%3Fa%3Da');
// return "/demo/中文/test%3Fa%3Da"

How can I do this?



Solution 1:[1]

String url = "/demo/%E4%B8%AD%E6%96%87/test%3Fa%3Da";
StringJoiner decoded = new StringJoiner("/");

String[] splittedUrl = url.split("/");
for (String item : splittedUrl) {
    if (!item.startsWith("%")) {
        decoded.add(item);
    } else {
        decoded.add(URLDecoder.decode(item, StandardCharsets.UTF_8));
    }
}
System.out.println(decoded); // /demo/??/test%3Fa%3Da

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1