Building url using Uri in Android

The examples below will build a url string
https://api.example.com/search?id=123&category=student

1. imports

import android.net.Uri;
import java.net.URL;

2. Build url using Uri.Builder

private String uriBuilder() {
    Uri.Builder builder = new Uri.Builder();
    builder.scheme("https")
            .authority("api.example.com")
            .appendPath("search")
            .appendQueryParameter("id", "123")
            .appendQueryParameter("category", "student");
    String myUrl = builder.build().toString();
    return myUrl;
}

3. Build url using Uri.parse

private String uriParser() {
    Uri builtUri = Uri.parse("https://api.example.com/")
            .buildUpon()
            .path("search")
            .appendQueryParameter("id", "123")
            .appendQueryParameter("category", "student")
            .build();
    try {
        URL url = new URL(builtUri.toString());
        return url.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search