HttpUrl newBuilder(String) usage

Viewed 1750

To create new HttpUrl.Builder instance from existing URL I use HttpUrl.newBuilder(String):

new HttpUrl().build().newBuilder(savedUrl)

where savedUrl is a String containing well-formed URL.

The above fragment crashes in HttpUrl constructor because of scheme is undefined. As a workaround I use existing HttpUrl instance - less than ideal.

The questions are:

  1. is newBuilder(String) the right tool for the job?
  2. how newBuilder(String) should be used properly?
2 Answers

Use parse to create a new builder from an existing well-formed URL string:

HttpUrl.Builder urlBuilder = HttpUrl.parse(savedUrl).newBuilder();

Here, you can add query parameters etc. and then call urlBuilder.build() to get the final HttpUrl.

Use newBuilder(String) to resolve relative links.

 HttpUrl.get("https://example.com/a.html")
     .newBuilder("b.html")
Related