PaulEdison
PaulEdison

Reputation: 947

What is the right way to safely concatenate an URL without forgetting a separator?

lets assume I have some method like that:

void getMagicUrl(Sting urlBase, String addedPath) {
    urlBase = urlBase.endsWith("/") ? urlBase : urlBase + "/";      // *1*
    urlBase = urlBase + "constantPath/";                            // *2*
    urlBase = urlBase + addedPath;                                  // *3*
    return new URL(urlBase);                                        // *4*
}

Is there with Java (8) no better way to concatenate the URL together and not to check manual for the ending / as path separator to not forget it? (Like in line 1)
and have it in the path names always? (like in line 2)

or does the JDK have something in there?

Upvotes: 2

Views: 3232

Answers (2)

Víctor Cabrera
Víctor Cabrera

Reputation: 56

There are more alternatives to build a url in both type-safety and fluent way. They involve adding new dependencies but some of them are very common and useful.

Apache commons (JavaDoc)

URI uri = new URIBuilder()
        .setHost("your_host")
        .setPath("/you_path")
        .setParameter("param1", "value1")
        .build();

uri.toString();

JAX-RS (JavaDoc)

URI uri= UriBuilder
    .fromPath("your_domain")
    .scheme("http")
    .path("your_path/")
    .queryParam("param1", "value1")
    .build();

URI uri = builder.build();

OkHttp (JavaDoc) (GitHub)

URL url = new HttpUrl.Builder()
        .scheme("http")
        .host("your_domain")
        .addPathSegments("your_path")
        .addQueryParameter("param1", "value1")
        .build()
        .url();

If you want to use Java 8 without additional dependencies, you could use URI class' constructor directly but it's not so friendly as the previous alternatives.

URI class (JavaDoc)

URI uri = new URI("your_host", "your_path", "param1=value1");

Upvotes: 3

pvpkiran
pvpkiran

Reputation: 27018

One of the most efficient ways to build url is to use UriComponentsBuilder

Something like this

 UriComponents uriComponents = UriComponentsBuilder.newInstance()
      .scheme("http").host("www.blahblah.com).path("/somepath").build().encode();

 uriComponents.toUriString());

This avoids all the manual concatenation using +

There are many methods to add path variables and query params and much more. Here is a nice article on it.

Upvotes: 3

Related Questions