Sam Chen
Sam Chen

Reputation: 8917

Why do we need to call "build()" for Uri.Builder object to pass in URL constructor?

I'm learning URL right now, and I get confused when I am building the Uri and pass it into the URL constructor.

I found that most of people use build() for the Uri.Builder object and then pass it (using toString()) into the URL constructor. However, I found that I can just pass my UriBuilder object and use toString() into the URL constructor, which also works. So, what's the differences? What's the pros and cons?

public static URL buildUrl(String githubSearchQuery) {
    Uri.Builder uriBuilder = Uri.parse(GITHUB_BASE_URL).buildUpon();

    uriBuilder.appendQueryParameter(PARAM_QUERY, githubSearchQuery);
    uriBuilder.appendQueryParameter(PARAM_SORT, sortBy);

    //Uri uri = uriBuilder.build();

    URL url = null;

    try {
        url = new URL(uriBuilder.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return url;
}

Thank you.

Upvotes: 0

Views: 597

Answers (1)

davidxxx
davidxxx

Reputation: 131556

The java.net.URL has overloaded constructors : one of them accepts an URI and another accepts a String.
So both are valid :

url = new URL(uriBuilder.toString()); // pass a String
url = new URL(uriBuilder.build());  //  pass an android.net.Uri

This works in both cases because UriBuilder.toString() is overrided to render the current building URI in its textual classic format :

  public String toString() {
        @SuppressWarnings("StringEquality")
        boolean cached = cachedString != NOT_CACHED;
        if (cached) {
            return cachedString;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(scheme).append(':');
        sb.append(getEncodedSchemeSpecificPart());
        if (!fragment.isEmpty()) {
            sb.append('#').append(fragment.getEncoded());
        }
        return cachedString = sb.toString();
    }

But this is a kind of trick because toString() even if not likely could change its implementation in a next version that would not allow you to pass it as a valid textual URI to the URL constructor.

Upvotes: 1

Related Questions