How do I retrieve a URL in Java?

Is there an open source URL manipulation library in Java?

  • The requirements: Conversion to/from String, like http://java.net.URL Extraction and manipulation of parameters, both query and hash (for JavaScript apps) Access to the parts of the URL: scheme, host, path

  • Answer:

    Adam is correct in that there is no single library that does everything you want. The http://java.net.URI class does some of what you want (bullets 1 & 2) but it does not handle the second one too great. For that, you might want to take a look at the URI Templates spec (RFC6570): http://tools.ietf.org/html/rfc6570 It allows you to define a define a URI expression with variables and inject replacement variables into it. It's a formalization of the URI Templates in JAX-RS. I maintain a Java implementation that is compliant with the spec here: https://github.com/damnhandy/Handy-URI-Templates Have a look at the unit tests for detailed examples. I'm expanding the API to allow dynamic construction of template expressions, similar to the JAX-RS UriBuilder. Ryan-

Ryan J. McDonough at Quora Visit the source

Was this solution helpful to you?

Other answers

No there is not a single library. You will have to cobble a bunch together. At one point Guava looked like they were going to include URI stuff but it seems they held off: http://code.google.com/p/guava-libraries/issues/detail?id=1005 I also discussed this in my blog post here: http://adamgent.com/post/7935905516/parsing-and-converting-common-formats-in-java Basically it boils down to three or four libraries. URI Building (Jersey's URIBuilder) URL Query Parsing (Commons Http Components Client: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html) URI encoding/decoding (Spring or Commons Http Old Client or use my Gist: https://gist.github.com/3011049). You should also know that URL's in the wild are not really a subset of URI's: http://adamgent.com/post/25161273526/urls-are-not-a-subset-of-uris That is don't expect the HttpServletRequest.getRequestUri() to actually give you a  valid URI: http://stackoverflow.com/questions/11038967/brackets-in-a-request-url-are-legal-but-not-in-a-uri-java.

Adam Gent

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.