android - how to access api with api_key Using Retrofit -


i new on android.can 1 tell me how add header api_key using retrofit.i not able understand how can this.

i find code net.where have put code in android folder structure.i confused this.where have add api_key.

// define interceptor, add authentication headers interceptor interceptor = new interceptor() {   @override   public okhttp3.response intercept(chain chain) throws ioexception {     request newrequest = chain.request().newbuilder().addheader("user-agent", "retrofit-sample-app").build();     return chain.proceed(newrequest);   } };  // add interceptor okhttpclient okhttpclient.builder builder = new okhttpclient.builder(); builder.interceptors().add(interceptor); okhttpclient client = builder.build();  // set custom client when building adapter retrofit retrofit = new retrofit.builder()   .baseurl("https://api.github.com")   .addconverterfactory(gsonconverterfactory.create())   .client(client)   .build(); 

you can store api_key in strings.xml file this:

<string name="your_api_key_id" translatable="false">your_api_key</string> 

then, in okhttpclient definition class, write method build okhttpclient that:

private final static string api_key_identifier = "key_identifier";  private okhttpclient gethttpclient(){         okhttpclient.builder httpclient = new okhttpclient.builder();         httpclient.addinterceptor(new interceptor() {             @override             public response intercept(chain chain) throws ioexception {                 request original = chain.request();                 httpurl originalurl = original.url();                 httpurl url = originalurl.newbuilder()                         .addqueryparameter(api_key_identifier, mcontext.getstring(r.string.your_api_key_id))                         .build();                 request.builder requestbuilder = original.newbuilder().url(url);                 request request = requestbuilder.build();                 return chain.proceed(request);             }         });         return httpclient.build();     } 

you should implement client builder class singleton pattern, in order have client build centralized in 1 place inside code


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -