Android RETROFIT2&OKHTTP3 Add a unified request headers header

Source: Internet
Author: User

When using retrofit, it is sometimes necessary to set the Set-cookie and other request headers, if each URL is required, then a direct interceptor is good.

Official Note:

  • OKHTTP3 under Okhttpclient list< interceptor> interceptors () method, returns a list that is not editable, If you edit it, it will be reported unsupportedoperationexception
  • The typical usage scenario for interceptor is to edit the headers of the request and the response.

As shown in the following:

Pay attention to the header, do not copy, to use flexibly.

Have all network requests enclosed with your token:

new Interceptor() {    @Overridepublicinterceptthrows IOException {        Request originalRequest = chain.request();        ifnull || alreadyHasAuthorizationHeader(originalRequest)) {            return chain.proceed(originalRequest);        }        Request authorised = originalRequest.newBuilder()            .header("Authorization", Your.sToken)            .build();        return chain.proceed(authorised);    }};

Add more than two interceptors to the okhttpclient, as shown in the following code:

 Public  class restdatasource implements Repository {    Private FinalMarvelservice Mmarvelservice;@Inject     Public Restdatasource() {//Log informationHttplogginginterceptor Logginginterceptor =NewHttplogginginterceptor (); Logginginterceptor.setlevel (HttpLoggingInterceptor.Level.BASIC);//private keyMarvelsigninginterceptor Signinginterceptor =NewMarvelsigninginterceptor (Buildconfig.marvel_public_key, Buildconfig.marvel_private_key);//How to use OkHttp3.0Okhttpclient client =NewOkhttpclient.builder (). Addinterceptor (Signinginterceptor). Addinterceptor (Loggingintercepto R). build ();//Select people informationGson customgsoninstance =NewGsonbuilder (). Registertypeadapter (NewTypetoken<list<avengerscharacter>> () {}.gettype (),NewMarvelresultsdeserializer<avengerscharacter> ()). Create ();//AdapterRetrofit Marvelapiadapter =NewRetrofit.builder (). BASEURL (Marvelservice.end_point). Addconverterfactory (Gsonconverterfacto Ry.create (Customgsoninstance)). Addcalladapterfactory (Rxjavacalladapterfactory.create ()). Cl Ient (client). Build ();//ServicesMmarvelservice = Marvelapiadapter.create (Marvelservice.class); }//Return people information    @Override     PublicObservable<list<avengerscharacter>>getcharacters(intCurrentoffset) {returnMmarvelservice.getcharacters (Currentoffset); }}

Here's a complete configuration:

ImportOKHTTP3. Interceptor;ImportOKHTTP3. Okhttpclient;ImportOKHTTP3. Request;ImportOKHTTP3. Response;ImportRetrofit2. Retrofit; Public  class retrofitapimanager {     Public Static FinalString Server_url ="url"; Public StaticClientapiProvideclientapi() {Retrofit Retrofit =NewRetrofit.builder (). BASEURL (Server_url). Client (Genericclient ()). build ();returnRetrofit.create (Clientapi.class); } Public StaticOkhttpclientgenericclient() {Okhttpclient httpClient =NewOkhttpclient.builder (). Addinterceptor (NewInterceptor () {@Override                     PublicResponseIntercept(Chain Chain)throwsIOException {Request request = Chain.request (). Newbuilder () . AddHeader ("Content-type","application/x-www-form-urlencoded; Charset=utf-8 "). AddHeader ("Accept-encoding","gzip, deflate"). AddHeader ("Connection","Keep-alive"). AddHeader ("Accept","*/*"). AddHeader ("Cookie","Add cookies Here"). build ();returnChain.proceed (Request); }}). Build ();returnHttpClient; }}

Android RETROFIT2&OKHTTP3 Add a unified request header headers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.