Use URI builder in Android or create URL with variables

Use URI builder in Android or create URL with variables

Lets say that I want to create the following URL:

https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name

To build this with the Uri.Builder I would do the following.

Uri.Builder builder = new Uri.Builder();
builder.scheme(https)
    .authority(www.myawesomesite.com)
    .appendPath(turtles)
    .appendPath(types)
    .appendQueryParameter(type, 1)
    .appendQueryParameter(sort, relevance)
    .fragment(section-name);
String myUrl = builder.build().toString();

There is another way of using Uri and we can achieve the same goal

http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7

To build the Uri you can use this:

final String FORECAST_BASE_URL = 
    http://api.example.org/data/2.5/forecast/daily?;
final String QUERY_PARAM = q;
final String FORMAT_PARAM = mode;
final String UNITS_PARAM = units;
final String DAYS_PARAM = cnt;

You can declare all this the above way or even inside the Uri.parse() and appendQueryParameter()

Uri builtUri = Uri.parse(FORECAST_BASE_URL)
    .buildUpon()
    .appendQueryParameter(QUERY_PARAM, params[0])
    .appendQueryParameter(FORMAT_PARAM, json)
    .appendQueryParameter(UNITS_PARAM, metric)
    .appendQueryParameter(DAYS_PARAM, Integer.toString(7))
    .build();

At last

URL url = new URL(builtUri.toString());

Use URI builder in Android or create URL with variables

Excellent answer from above turned into a simple utility method.

private Uri buildURI(String url, Map<String, String> params) {

    // build url with parameters.
    Uri.Builder builder = Uri.parse(url).buildUpon();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.appendQueryParameter(entry.getKey(), entry.getValue());
    }

    return builder.build();
}

Leave a Reply

Your email address will not be published.