Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a right way to build a URL? [duplicate]

Tags:

java

url

uri

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".

like image 582
OldCurmudgeon Avatar asked Oct 23 '13 09:10

OldCurmudgeon


People also ask

Can URL be duplicated?

This means that the URL in question is technically identical to at least one other indexable URL. This could be URLs that are only different based on case, or have the same query string parameters and values (but in a different order).

Does duplicate copy Hurt SEO?

Is Duplicate Content Bad For SEO? Officially, Google does not impose a penalty for duplicate content. However, it does filter identical content, which has the same impact as a penalty: a loss of rankings for your web pages.

Does duplicate content still hurt your SEO in 2020?

Is Duplicate Content Damaging for SEO? Yes, but not always with Google penalties or manual actions. Webmasters unintentionally create the vast majority of cases of duplicate content SEO. While technically not a penalty, duplicate content can still have an impact on search engine rankings.


1 Answers

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

like image 123
Barun Avatar answered Sep 20 '22 17:09

Barun