Is there a right way to build a URL?

OldCurmudgeon picture OldCurmudgeon · Oct 23, 2013 · Viewed 79.2k times · Source

In much of the code I work with there is horrible stuff like:

String url = "../Somewhere/SomeServlet?method=AMethod&id="+object.getSomething()+ "&aParam="+object.getSomethingElse());

or - even worse:

String url = "Somewhere/Here/Something.jsp?path="+aFile.toString().replace("\\","/")+ "&aParam="+object.getSomethingElse());

Is there a right way to:

  1. Create a new URL (or is it a URI).
  2. Add correctly escaped parameters to it.
  3. Add well-formed file paths in those params.
  4. Resolve it to a String.

Essentially - it is too easy to just build the string than it is to do it properly. Is there a way to do it properly that is as easy as just building the string?

Added

For clarity - and after a little thought - I suppose I am looking for something like:

String s = new MyThing()
    .setPlace("Somewhere/Something.jsp")
    .addParameter(aName,aValue)
    .addParameter(aName,aFile)
    .toString();

so that it will deal with all of the unpleasantness of escaping and adding "?"/"&" and changing "\" to "/" instead of using "\" for files etc.

If I have to write one myself (i.e. if Apache is not an option) are there real Java techniques for correctly escaping the various parts. I mean things like escaping " " in parameters as "." while escaping " " in other places a "%20".

Answer

Barun picture Barun · Oct 23, 2013

You can use Apache URIBuilder

Sample code: Full Apache Example

URIBuilder builder = new URIBuilder()
    .setScheme("http")
    .setHost("apache.org")
    .setPath("/shindig")
    .addParameter("helloWorld", "foo&bar")
    .setFragment("foo");
builder.toString();

Output: http://apache.org/shindig?helloWorld=foo%26bar#foo