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:
- Create a new URL (or is it a URI).
- Add correctly escaped parameters to it.
- Add well-formed file paths in those params.
- 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".
You can use Apache URIBuilder
Sample code: Full Apache Example
Output: http://apache.org/shindig?hello+world=foo%26bar#foo
I have written this up, you can change it where you want extra functionality. It doesn't use any external resources, let me know if I have looked over something!
It's basically a wrapper for the
URI
class that allows you to more easily add subdirectories and parameters to the URI. You can set default values if you're not interested in some things.Edit: I have added an option to use a relative URI (per your question).
Output:
Absolute
Relative
Recomendations
and in the code to build the URL.
You can also use spring UriComponentsBuilder
I like @Jeroen's suggestion but it didn't quite do all I wanted so, using his idea of gathering the parts together and then using a
URI
to grow the final result I put together this solution which seems to do what I want: