Pages - Menu

Thứ Năm, 2 tháng 6, 2016

Creating URL in Android

There are two ways to create a URL :

-The first way : Using Uri.Builder class

 Let's say that i want to create the following URL :
https://www.myawesomesite.com/turtles/types?type=1&sort=relevance#section-name
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");
URL myUrl = new URL(builder.build().toString);

-The second way : when we just need to append/add variables to the available URL

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

To build the Uri you can even 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());

Source : http://stackoverflow.com/questions/19167954/use-uri-builder-in-android-or-create-url-with-variables

Không có nhận xét nào:

Đăng nhận xét