programing

Android에서 URI 빌더를 사용하거나 변수가있는 URL을 작성하십시오.

new-time 2020. 5. 13. 21:26
반응형

Android에서 URI 빌더를 사용하거나 변수가있는 URL을 작성하십시오.


Android 앱을 개발 중입니다. API 요청을하려면 앱의 URI를 빌드해야합니다. URI에 변수를 넣는 다른 방법이 없다면 이것이 내가 찾은 가장 쉬운 방법입니다. 나는 당신이 사용해야한다는 것을

Uri.Builder

알았지 만 어떻게 해야할지 잘 모르겠습니다. 내 URL은 다음과 같습니다

http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value 

내 체계는 http, authority is

lapi.transitchicago.com

, path is

/api/1.0

, path segment (s) is

ttarrivals.aspx

, query string is

key=[redacted]&mapid=value

입니다.내 코드는 다음과 같습니다.

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);

나는 할 수 있음을 이해

URI.add

하지만 어떻게 그것을 통합 할 수

Uri.Builder

있습니까? 내가 좋아하는 모든 것을 추가해야합니다

URI.add(scheme)

,

URI.add(authority)

과 정도? 아니면 그렇게 할 수 있습니까? 또한 URI / URL에 변수를 추가하는 다른 쉬운 방법이 있습니까?


다음 URL을 만들고 싶다고 가정 해 봅시다.

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

이것을 사용하여 빌드하려면

Uri.Builder

다음을 수행하십시오.

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();

사용하는 다른 방법이

Uri

있으며 동일한 목표를 달성 할 수 있습니다

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

Uri를 빌드하려면 이것을 사용할 수 있습니다

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";

당신이 모든 위의 방법을 선언하거나 할 수 있습니다, 심지어 내부

Uri.parse()

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();

마침내

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

위에서 훌륭한 대답은 간단한 유틸리티 방법으로 바뀌 었습니다.

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();
}

여기에 설명하는 좋은 방법이 있습니다.URI에는 두 가지 형태가 있습니다1 - 빌더 (준비

수정

,

하지

준비를

사용

)2 - 내장 (

하지

준비가 될

수정

, 준비 할

사용

)당신은 빌더를 만들 수 있습니다

Uri.Builder builder = new Uri.Builder();

이렇게하면

빌더

를 다음과 같이 수정할 수 있습니다.

builder.scheme("https");
builder.authority("api.github.com");
builder.appendPath("search");
builder.appendPath("repositories");
builder.appendQueryParameter(PARAMETER_QUERY,parameterValue);

but to use it you have to build it first

retrun builder.build();

or however you gonna use it. and then you have built that is already built for you, ready to use but cannot be modified.

Uri built = Uri.parse("your URI goes here");

this is ready to use but if you want to modify it you need to buildUpon()

Uri built = Uri.parse(Your URI goes here")
           .buildUpon(); //now it's ready to be modified
           .buildUpon()
           .appendQueryParameter(QUERY_PARAMATER, parameterValue) 
           //any modification you want to make goes here
           .build(); // you have to build it back cause you are storing it 
                     // as Uri not Uri.builder

now every time you want to modify it you need to buildUpon() and in the end build().

so Uri.Builder is a Builder type that store a Builder in it. Uri is a Built type that store an already built URI in it

new Uri.Builder(); rerurns a Builder. Uri.parse("your URI goes here") returns a Built

and wiht build() you can change it from Builder to Built. buildUpon() you cam change it from Built to Builder here is what you can do

Uri.Builder builder = Uri.parse("URL").buildUpon();
// here you created a builder, made an already built URI with Uri.parse
// and then change it to builder with buildUpon();
Uri built = builder.build();
//when you want to change your URI, change Builder 
//when you want to use your URI, use Built

and also the opposite:-

Uri built = new Uri.Builder().build();
// here you created a reference to a built URI
// made a builder with new Uri.Builder() and then change it to a built with 
// built();
Uri.Builder builder = built.buildUpon();

hope my answer helped :) <3


for the example in the second Answer I used this technique for the same URL

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

Uri.Builder builder = new Uri.Builder();
            builder.scheme("https")
                    .authority("api.openweathermap.org")
                    .appendPath("data")
                    .appendPath("2.5")
                    .appendPath("forecast")
                    .appendPath("daily")
                    .appendQueryParameter("q", params[0])
                    .appendQueryParameter("mode", "json")
                    .appendQueryParameter("units", "metric")
                    .appendQueryParameter("cnt", "7")
                    .appendQueryParameter("APPID", BuildConfig.OPEN_WEATHER_MAP_API_KEY);

then after finish building it get it as URL like this

URL url = new URL(builder.build().toString());

and open a connection

  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

and if link is simple like location uri, for example

geo:0,0?q=29203

Uri geoLocation = Uri.parse("geo:0,0?").buildUpon()
            .appendQueryParameter("q",29203).build();

Using appendEncodePath() could save you multiple lines than appendPath(), the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());

You can do that with lambda expressions;

    private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";

    private String getBaseUrl(Map<String, String> params) {
        final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
        params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
        return builder.build().toString();
    }

and you can create params like that;

    Map<String, String> params = new HashMap<String, String>();
    params.put("zip", "94043,us");
    params.put("units", "metric");

Btw. If you will face any issue like “lambda expressions not supported at this language level”, please check this URL;

https://stackoverflow.com/a/22704620/2057154

참고URL : https://stackoverflow.com/questions/19167954/use-uri-builder-in-android-or-create-url-with-variables

반응형