I'm developing an Android app. I need to build a URI for my app to make an API request. Unless there's another way to put a variable in a URI, this is the easiest way I've found. I found that you need to use Uri.Builder
, but I'm not quite sure how to. My url is:
http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value
My scheme is http, authority is lapi.transitchicago.com
, path is /api/1.0
, path segment(s) is ttarrivals.aspx
, and query string is key=[redacted]&mapid=value
.
My code is below:
Intent intent = getIntent();
String value = intent.getExtras().getString("value");
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("www.lapi.transitchicago.com")
.appendPath("api")
.appendPath("1.0")
.appendPath("ttarrivals.aspx")
.appendQueryParameter("key", "[redacted]")
.appendQueryParameter("mapid", value);
I understand that I can do URI.add
, but how do I integrate it into the Uri.Builder
? Should I add everything like URI.add(scheme)
, URI.add(authority)
and so on? Or is that not the way to do it? Also, is there any other easier way to add a variable to a URI/URL?
Let's 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();