Java – why is the URL not fully decoded?

I'm writing a java program. My URL needs to be decoded. I'm using it

URLDecoder.decode(url,"UTF-8")

How to implement it Unfortunately, it is not fully decoded For example The above method decodes = to =, + to, but it does not decode a few characters, such as: / remains unchanged even after decoding Please tell me if I lose anything

Solution

First of all, everything works as expected Your problem is that the input string is encoded twice So simply decode it twice

Example:

>Input:% 3A > decode as: > decode as:

Code:

String input = "40.2%2522%26url%3Dhttp%253A%252F%252Fr1";
String output1 = URLDecoder.decode(input,"UTF-8");
String output2 = URLDecoder.decode(output1,"UTF-8");
System.out.println(input);
System.out.println(output1);
System.out.println(output2);

Output:

40.2%2522%26url%3Dhttp%253A%252F%252Fr1
40.2%22&url=http%3A%2F%2Fr1
40.2"&url=http://r1

Note: if you are not sure how many times the string is encoded, you can repeat the decoding until the result remains unchanged

String input = "40.2%2522%26url%3Dhttp%253A%252F%252Fr1";
String output = input;

do {
    input = output;
    output = URLDecoder.decode(input,"UTF-8");

} while (!input.equals(output));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>