Android Discovery based on Okhttp build your own Web request <Retrofit+Okhttp> (v)

Source: Internet
Author: User

Objective:

Through the above study, we can not find the simple use of okhttp to serve as a network library or how much to receive a little bit less convenient, but also need to manage the interface, for the interface of the use of what kind of request is not at a glance, for this purpose next study retrofit+ Okhttp with the use of a combination.

Retrofit Introduction:

Retrofit and Okhttp, also square open Source Library, it is a type of secure network Request library, retrofit simplifies the network request process, based on the okhtttp did the encapsulation, decoupling more thoroughly: for example, through annotations to configure the request parameters, Using a factory to generate Calladapter,converter, you can use different request adapters (Calladapter), such as 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 in the Build.gradle
Compile ' com.squareup.retrofit2:retrofit:2.0.2 '
2.) Initialize Retrofit
     New Retrofit.builder ()                . BASEURL (Base_url)                . Addconverterfactory (Fastjsonconverterfactory.create ())                . Client (Mokhttpclient)                . Build ();
3.) Initialize Okhttpclient
 Okhttpclient.builder Builder = new   OKHTTPC Lient (). Newbuilder (). ConnectTimeout ( ten, timeunit.seconds) // 
   
     Set the time-out period . ReadTimeout (timeunit.seconds) 
    // 
     Set the read time-out period . WriteTimeout (Timeunit.seconds); 
    //        
     int  cacheSize = 10 * 1024 * 1024; //         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, no more explanations here.

4.) About Converterfactory

For the initialization of okhttpclient we are already very familiar with the converterfactory first contact somewhat unfamiliar, in fact, this is used to unify the analysis of 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, it can only customize the converterfactory itself, but there is already a great God in the country to encapsulate it (HTTP://WWW.TUICOOL.COM/ARTICLES/J6RMYI7).

    • Fastjson compile ' org.ligboy.retrofit2:converter-fastjson-android:2.0.2 '

Focus on The realization of the factory class

Abstract classFactory { PublicConverter<responsebody,?>responsebodyconverter (type type, annotation[] annotations, Retrofit Retrofit) {return NULL; }     Publicconverter<?, requestbody>requestbodyconverter (type type, annotation[] parameterannotations, annotation[] methodannotations, Retrofit re Trofit) {return NULL; }     Publicconverter<?, string>stringconverter (type type, annotation[] annotations, Retrofit Retrofit) {return NULL; }  }

5.) Define interface GET request

1.get request without any parameters

 Public Interface Iapi {@GET ("users")// without parameter get requests    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 );

3.get Request stitching parameter @QueryMap use

 Public Interface Iapi {@GET ("Users/{groupid}")    call <List<User>> getusers (@Path ("UserId") String userId, @QueryMap hashmap<string, string> paramsmap);}
6.) Define the interface post request

1.post Request @body Use

 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 urlencodedcall    <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")/// no parameter GET request     call<list<user>> getusers ();}
8.) Request to use

1. Return to Iapi

    /**      * Initialize API     *    /privatevoid  Initiapi () {        = Retrofit.create (Iapi.  Class);    }     /**      * Return API     */public    static  Iapi API ()        { return api.iapi;    }

2. Sending the request

    Call<string> call = Api.api (). Login (Userid,password);    Call.enqueue (new callback<string>() {    @Override    publicvoid Onresponse (call<string> call, response<string> Response) {        log.e ("", "Response---- > "+ response.body ());        Request_tv.settext (Response.body ());    }    @Override    publicvoid onfailure (call<string> call , Throwable t) {        LOG.E ("", "response----failure");    }    );

Android Discovery based on Okhttp build your own Web request <Retrofit+Okhttp> (v)

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.