Home > other >  Java - how to build an URI using a query string that is already escaped?
Java - how to build an URI using a query string that is already escaped?

Time:01-28

LATER EDIT: not same problem as the suggested answer. In my case, I need to build the URI, relying on the fact that the original query string is not modified.


I have a String (coming from a request query String) that is already correctly escaped, like param1=/folder1/folder2/folder&name 2&param2=9481dxcv234.

The decoded value of param1 is /folder1/folder2/folder&name 2. Obviously, I cannot unescape that String (because of the & char in this value)...

I need to build an URI which has that original string as query value.

I tried using org.apache.http.client.utils.URIBuilder but could not get it to work: if I provide the original String to the URI(... constructor, the resulting URL is double-escaped, like param1=%2Ffolder1%2Ffolder2%2Ffolder%26name%202&param2=9481dxcv234.

Can I somehow do what I need ? To build an URI by passing the query string already escaped and leave it unchanged ?

Thanks.

CodePudding user response:

I think, the simplest way is unescape it first. Then you can work with url as usualy.

CodePudding user response:

You could use org.springframework.web.util.UriComponentsBuilder:

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
UriComponents components = builder.build();
MultiValueMap<String, String> parameters = components.getQueryParams();

parameters.get("param1") //"/folder1/folder2/folder&name 2"

You can then URLDecode to get what you need.

Edit:

Since you appear to be using Apache HttpClient,

List<NameValuePair> params = org.apache.http.client.utils.URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8"));

params.get("param1") //"/folder1/folder2/folder&name 2"
  •  Tags:  
  • Related