Home > Back-end >  How to avoid special character from URL using java
How to avoid special character from URL using java

Time:09-12

I am using below code to eliminate the special characters from URL:

String url1 = "https://dev/ABC/v1/XYZ?itemnumber%5Bin%5D=%5B3001%2C3005%2C202%5D&limit=2&apikey=4zVYEk2Xg8zvwYxNnW&offset=2";

String decodedURL = URLDecoder.decode(url1, "UTF-8");

System.out.println(decodedURL);

Expected output:

https://dev/ABC/v1/XYZ?itemnumber[in]=[3001,3005,20]&limit=2&offset=1&apikey=4zVYEk2Xg8zvwYxNnW

Error output:

https://dev/ABC/v1/XYZ?itemnumber[in]=[3001,3005,202]&limit=2&apikey=4zVYEk2Xg8zvwYxNnW&offset=1

CodePudding user response:

Your string is double-URL encoded, see https://ideone.com/CQQbPz:

String url1 = "https://dev/ABC/v1/XYZ?itemnumber%5Bin%5D=%5B3001%2C3005%2C202%5D&limit=2&apikey=4zVYEk2Xg8zvwYxNnW&offset=2";

System.out.println(URLDecoder.decode(url1, "UTF-8"));
System.out.println(URLDecoder.decode(URLDecoder.decode(url1, "UTF-8"), "UTF-8"));

Output:

https://dev/ABC/v1/XYZ?itemnumber[in]=[3001,3005,202]&limit=2&apikey=4zVYEk2Xg8zvwYxNnW&offset=2
https://dev/ABC/v1/XYZ?itemnumber[in]=[3001,3005,202]&limit=2&apikey=4zVYEk2Xg8zvwYxNnW&offset=2

CodePudding user response:

Browsers and many other http programs convert illegitimate url request symbols to URL encoding scheme that place a % percent sign in front of two numerals. Before use, use

String decoded = java.net.URLDecoder.decode(request);
  • Related