Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse and decode URI in Java to URI components?

Tags:

java

url

decode

I am trying to find a method that would parse an URL, decoded it and returned the decoded components in an unambiguous way.

URLDecoder isn't a right fit, because it may return ambiguous String, e.g.

URLDecoder.decode("http://www.google.com?q=abc%26def", "UTF-8")

returns:

http://www.google.com?q=abc&def 

So the information about escaped & is lost.

I'd like to have something like:

DecodedUrlComponents cmp = GreatURLDecoder.decode(url);
Map<String, List<String>> decodedQuery = cmp.getQuery();
decodedQuery.get("q").get(0); //returns "abc&def"

How do I accomplish that?

EDIT: Thanks for the responses, but my question was a bit different: I would like to get decoded components in an unambiguous way, so neither of the following does what I need:

  • new URI("http://www.google.com?q=abc%26def").getRawQuery() returns encoded query: q=abc%26def
  • new URI("http://www.google.com?q=abc%26def").getQuery() returns ambiguous value: q=abc&def
  • URLDecoder.decode("http://www.google.com?q=abc%26def", "UTF-8") returns ambiguous value: http://www.google.com?q=abc&def
  • org.springframework.web.util.UriComponentsBuilder.fromUriString("http://www.google.com?q=abc%26def").build(true).getQueryParams() - close, but still not what I want, because it returns a map of encoded params: {q=[abc%26def]}
like image 561
tomkur Avatar asked Mar 17 '15 10:03

tomkur


2 Answers

With spring framework (org.springframework.web.util) you can do the following:

URI uri = <your_uri_here>;
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri);
UriComponents uriComponents = uriComponentsBuilder.build();
String path = uriComponents.getPath();
MultiValueMap<String, String> queryParams = uriComponents.getQueryParams(); //etc.
like image 99
yvs Avatar answered Oct 16 '22 13:10

yvs


You could for example use an implementation of javax.ws.rs.core.UriInfo. One example would be org.jboss.resteasy.spi.ResteasyUriInfo. If you're using maven you only need to add the following to your pom.xml:

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.0.6.Final</version>
</dependency>

Then the following code should do what you want:

UriInfo ui = new ResteasyUriInfo(new URI("http://www.google.com?q=abc%26def"));
List<String> qValues = ui.getQueryParameters().get("q");
for (String q : qValues) {
    System.out.println(q);
}
like image 23
Petter Avatar answered Oct 16 '22 14:10

Petter