Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding URI query string in Java

I need to decode a URI that contains a query string; expected input/output behavior is something like the following:

abstract class URIParser {            /** example input:        * something?alias=pos&FirstName=Foo+A%26B%3DC&LastName=Bar */     URIParser(String input) { ... }     /** should return "something" for the example input */     public String getPath();      /** should return a map        * {alias: "pos", FirstName: "Foo+A&B=C", LastName: "Bar"} */     public Map<String,String> getQuery(); } 

I've tried using java.net.URI, but it seems to decode the query string so in the above example I'm left with "alias=pos&FirstName=Foo+A&B=C&LastName=Bar" so there is ambiguity whether a "&" is a query separator or is a character in a query component.

Edit: I just tried URI.getRawQuery() and it doesn't do the encoding, so I can split the query string with a &, but then what do I do? Javascript has decodeURIComponent, I can't seem to find the corresponding method in Java.

Any suggestions? I would prefer not to use any new libraries.

like image 438
Jason S Avatar asked Apr 13 '10 18:04

Jason S


People also ask

How do you encode and decode URL parameters in Java?

Encode the URL private String encodeValue(String value) { return URLEncoder. encode(value, StandardCharsets. UTF_8. toString()); } @Test public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception { Map<String, String> requestParams = new HashMap<>(); requestParams.

How do you decode a String in Java?

decode(encodedString); String actualString= new String(actualByte); Explanation: In above code we called Base64. Decoder using getDecoder() and then decoded the string passed in decode() method as parameter then convert return value to string.

What is URL decoder in Java?

public class URLDecoder extends Object. Utility class for HTML form decoding. This class contains static methods for decoding a String from the application/x-www-form-urlencoded MIME format. The conversion process is the reverse of that used by the URLEncoder class.


1 Answers

Use

URLDecoder.decode(proxyRequestParam.replace("+", "%2B"), "UTF-8")           .replace("%2B", "+") 

to simulate decodeURIComponent. Java's URLDecoder decodes the plus sign to a space, which is not what you want, therefore you need the replace statements.

Warning: the .replace("%2B", "+") at the end will corrupt your data if the original (pre-x-www-form-urlencoded) contained that string, as @xehpuk pointed out.

like image 114
janb Avatar answered Sep 22 '22 02:09

janb