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:
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
URIBuilder builder = new URIBuilder()
.setScheme("http")
.setHost("apache.org")
.setPath("/shindig")
.addParameter("helloWorld", "foo&bar")
.setFragment("foo");
builder.toString();