Android retrofit+okhttp guidelines for using HTTP network programming _android

Source: Internet
Author: User

Retrofit Introduction:
Retrofit (GitHub homepage https://github.com/square/okhttp) and Okhttp division, also square Open Source Library, it is a type of secure network request library, Retrofit simplifies the network request process, based on okhtttp encapsulation, decoupling is more thorough: for example, through annotations to configure request parameters, through the factory to generate Calladapter,converter, you can use a different request adapter (Calladapter), Let's say rxjava,java8, guava. You can use different deserialization tools (Converter), such as JSON, Protobuff, XML, Moshi, and so on.
Official website http://square.github.io/retrofit/
GitHub Https://github.com/square/retrofit

Retrofit use:
1. Add the following configuration to the Build.gradle

Compile ' com.squareup.retrofit2:retrofit:2.0.2 '

2. Initialization of Retrofit

   Retrofit = new Retrofit.builder ()
        . BaseURL (Base_url)
        . Addconverterfactory (fastjsonconverterfactory.create ())
        . Client (mokhttpclient)
        . Build ();

3. Initialization of Okhttpclient

    Okhttpclient.builder Builder = new Okhttpclient (). Newbuilder ()
        . ConnectTimeout (timeunit.seconds)/Set timeout time
        . ReadTimeout (timeunit.seconds)/Set the Read timeout
        . WriteTimeout (timeunit.seconds);/Set write timeout time
    int CacheSize = 10 * 1024 * 1024; A MiB
    Cache cache = New cache (App.getcontext (). Getcachedir (), cacheSize);
    Builder.cache (cache);
    Builder.addinterceptor (Interceptor);
    Mokhttpclient = Builder.build ();
About Okhttp interceptors, Cache-control, and so on, this is no longer a commentary.

4. About Converterfactory
for the initialization of okhttpclient we have been very familiar with the converterfactory initial contact with the number of unfamiliar, in fact, this is used to unify the resolution Responsebody return data.

The Common Converterfactory

Gson:com.squareup.retrofit2:converter-gson
Jackson:com.squareup.retrofit2:converter-jackson
Moshi: Com.squareup.retrofit2:converter-moshi
protobuf:com.squareup.retrofit2:converter-protobuf
Wire: Com.squareup.retrofit2:converter-wire simple
xml:com.squareup.retrofit2:converter-simplexml
Scalars ( Primitives, boxed, and String): Com.squareup.retrofit2:converter-scalars

Because Fastjson is used in the project, you can only customize Converterfactory.

5. Define interface GET request
(1) Get request without any parameters

Public interface Iapi {

  @GET ("users")//without parameter GET request
  call<list<user>> getusers ();

}

(2) Get request dynamic path @Path use

Public interface Iapi {

  @GET ("Users/{groupid}")//dynamic path GET request
  call<list<user>> getusers (@Path (" UserId ") String userId);




(3) Get request stitching parameter @Query use
Public interface Iapi {

  @GET ("Users/{groupid}")
  call<list<user>> getusers (@Path ("UserId") String userId, @Query (' age ') int age);



6. Define Interface POST request
(1) Post request @body use

The public interface Iapi {

  @POST ("add")//directly converts the object through converterfactory to the corresponding parameter
  call<list<user>> addUser (@Body user user);

}

(2) Post request @FormUrlEncoded, @Field use

Public interface Iapi {

 @POST ("login")
  @FormUrlEncoded//Read parameters urlencoded
  call<user> Login (@ Field ("UserId") string username, @Field ("password") string password);



(3) Post request @FormUrlEncoded, @FieldMap use

Public interface Iapi {

  @POST ("login")
  @FormUrlEncoded//Read parameters urlencoded
  call<user> Login (@ Fieldmap hashmap<string, string> paramsmap);

}

(4) Post request @Multipart, @Part use

Public interface Iapi {

  @Multipart
  @POST ("login")
  call<user> Login (@Part ("UserId") String userId, @ Part ("password") String password);



7.cache-control Cache Control

Public interface Iapi {

  @Headers ("cache-control:max-age=640000")
  @GET ("users")//without parameter GET request
  call< List<user>> getusers ();

}


8. Request to use
(1) return to Iapi
  /**
   * Initialization API *
  /private void Initiapi () {
    Iapi = retrofit.create (Iapi.class);
  }
  /**
   * Returns API
  /public static IAPI APIs () {return

    api.iapi;
  }


(2) Send request

  Call<string> call = Api.api (). Login (Userid,password);
  Call.enqueue (New callback<string> () {
  @Override public
  void Onresponse (call<string> call, Response<string> Response) {
    log.e ("", "Response---->" + response.body ());
  }

  @Override public
  void OnFailure (call<string> call, Throwable t) {
    log.e ("", "response----Failed");
  }
  );

9. Interceptor Configuration

Interceptor Configuration Essentials
Introducing Dependencies:
Compile ' com.squareup.retrofit2:retrofit:2.0.0-beta4 '
compile ' com.squareup.retrofit2:converter-gson:2.0.0- Beta4 '
compile ' com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4 '
compile ' com.squareup.okhttp3:o khttp:3.0.1 '
compile ' com.squareup.okhttp3:logging-interceptor:3.0.1 '
First said Okhttp 3.0 configuration, 3.0 use level of the main change is, from the original Okhttp object directly to the configuration of various sets to Builder configuration mode, so the original corresponding method should be found under the Okhttpclient.builder object. Some of my common configurations are as follows:
Httplogginginterceptor Interceptor = new Httplogginginterceptor ();
Interceptor.setlevel (HttpLoggingInterceptor.Level.BODY);
Okhttpclient client = new Okhttpclient.builder ()
    . Addinterceptor (Interceptor)
    . Retryonconnectionfailure ( true)
    . ConnectTimeout (timeunit.seconds).
    addnetworkinterceptor (mtokeninterceptor). Build
    ();
Explain:
(1) Httplogginginterceptor is a interceptor, used to output network requests and results of the LOG, can be configured level for basic/headers/body, are well understood, corresponding to the original retrofit set log leve L method, now retrofit has no this method, so only to okhttp this side to configure, and the body corresponds to the original to full.
(2) The Retryonconnectionfailure method makes a reconnection to the settings error.
(3) ConnectTimeout set timeout time
(4) Addnetworkinterceptor all network requests are attached to your interceptor, I set up here a token interceptor, that is, in all network requests header plus token parameters, the following will be a little bit about this content.
Have all the network requests attached to your interceptor:
Interceptor Mtokeninterceptor = new Interceptor () {
  @Override public Response intercept (Chain Chain) throws Ioexcepti On {
    Request originalrequest = Chain.request ();
    if (Your.stoken = null | | alreadyhasauthorizationheader (originalrequest)) {return
      chain.proceed (originalrequest );
    }
    Request authorised = Originalrequest.newbuilder ()
      . Header ("Authorization", Your.stoken)
      . Build ();
    return Chain.proceed (authorised);
  }
;
Explain:
(1) that if the judge means that if your token is empty, is not yet requested to token, such as for landing requests, there is no token, only wait until after landing token, this time do not attach token. Also, if you have a validation header in your request, such as if you manually set up an additional token, then you do not need to attach this token.
(2) header key is usually Authorization, if you are not this, you can modify.
(3) If you need to refresh token when encountering such as 401 not authorised, you can use authenticator, which is a specially designed interceptor that asks for access to processing when the validation error occurs:
Authenticator mauthenticator = new Authenticator () {
  @Override public Request Authenticate (Route Route, Response resp Onse)
      throws IOException {
    Your.stoken = Service.refreshtoken ();
    Return Response.request (). Newbuilder ().
            AddHeader ("Authorization", Newaccesstoken)
            . Build ();    
  }

Then, for the above two interceptors, use the Addnetworkinterceptor (Mtokeninterceptor) and authenticator of the Okhttpclient.builder object respectively (mauthenticator To
Retrofit:
For retrofit, my configuration is:
Retrofit RETROFIT = new Retrofit.builder ()
    . BaseURL (appconfig.base_url).
    Client (client)
    . Addcalladapterfactory (Rxjavacalladapterfactory.create ())
    . Addconverterfactory (gsonconverterfactory.create (Gson))
    . Build ();
Service = Retrofit.create (Yourapi.class);
Explain:
(1) BaseURL: The original setEndPoint method became BaseURL
(2) client is the OKHTTP3 object above
(3) addcalladapterfactory Add Rxjava Adapter
(4) addconverterfactory Add Gson Converter

Related Article

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.