Retrofit 2.0 based on okhttp more efficient and faster network framework and custom converters

Source: Internet
Author: User
Tags throwable

Time relationship, this article on the simple use of Retrofit 2.0 to explain as to the principle after the free to analyze

The project is comprehensive, simple and easy to understand address:

The simple use of Retrofit 2.0 is as follows: Https://gitee.com/bimingcong/MyRetrofit

Private voidInitget () {Retrofit Retrofit=NewRetrofit.builder (). BASEURL ("Http://v.juhe.cn/"). Addconverterfactory (Gsonconverterfactory.create ()). build (); GetService Service= Retrofit.create (GetService.class); FinalCall<getbean> call = Service.getstring3 ("Toutiao", "Shehui", "D05B58FA6901AD9BED77A1EF08BD6CCB"); Call.enqueue (NewCallback<getbean>() {@Override Public voidOnresponse (call<getbean> call, response<getbean>response) {                if(Response.issuccessful ()) {Getbean=Response.body (); }} @Override Public voidOnFailure (call<getbean>Call , Throwable t)    {                                         }        }); }

What GetService is the inside of the @query can actually be understood as a GET request URL? The key value pair of the string parameter behind it

 Public InterfaceGetService {//Direct stitching, remember to add a question mark@GET ("TOUTIAO/INDEX?TYPE=SHEHUI&AMP;KEY=D05B58FA6901AD9BED77A1EF08BD6CCB") Call<GetBean>getString (); //{name} can be simplest understood as a path substitution block, denoted by "{}", used in conjunction with the annotation @path, to understand the decoupling, parameter Name==toutiao@GET ("{NAME}/INDEX?TYPE=SHEHUI&AMP;KEY=D05B58FA6901AD9BED77A1EF08BD6CCB") Call<GetBean> getString2 (@Path ("name") String name); //for @get, parameter information can be uploaded directly to the URL.    Then you will react immediately, and there is a serious coupling as well! //So, there's @query.@GET ("{Name}/index") Call<GetBean> GetString3 (@Path ("name") String name, @Query ("type") String type, @Query ("Key") String key); //Suppose I want to upload 10 parameters in a parameter? Which means I'm going to declare 10 @query parameters in the method?    Of course not! //retrofit also considered this, so the needle for the complex parameter upload, for us to prepare the @querymap@GET ("{Name}/index") Call<GetBean> GetString4 (@Path ("name") String name, @QueryMap hashmap<string, string>HashMap); //General get has no request body, so directly get interface URL can be dynamic URL@GET () Observable<ResponseBody>getString5 (@Url String Url);}

The @field in the POST request can actually be interpreted as a post to submit a parameter key value pair which also has a single file and multiple file uploads

 Public InterfacePostservice {@FormUrlEncoded @POST ("Toutiao/index") Call<PostBean> poststring (@Field ("type") String type, @Field ("Key") String key); //Post form submission-Multiple parameters [email protected]@FormUrlEncoded @POST ("Toutiao/index") Call<PostBean> postString2 (@FieldMap hashmap<string, string>params); //Post file submission, each key value pair needs to use @part annotation key name//Multipart support File Upload@Multipart @POST ("Https://pan.baidu.com/disk/home?#/all?vmode=list&path=%2Fas") Call<TestBean> Postfile (@Part ("photo\"; filename=\ "test.png\" ") requestbody body); @Multipart @POST ("XXXX") Call<TestBean> PostFile2 (@PartMap hashmap<string, requestbody> Bodymap, @Field ("token") String token);}

The corresponding examples are as follows:

// What to do when I get the data successful     Public Interface Onsuccesslistener {        void  onsuccess (Object o);         void onfaile ();    }

 //provides methods to invoke the service entity class, requestbody upload a single file     Public voidUploadFile (Requestbody body,FinalOnsuccesslistener Listener) { Call<TestBean> call =Mservice.postfile (body); Call.enqueue (NewCallback<testbean>() {@Override Public voidOnresponse (call<testbean> call, response<testbean>response)            {listener.onsuccess (response); } @Override Public voidOnFailure (call<testbean>Call , Throwable t)            {Listener.onfaile ();    }        }); }

Converter:

As for the custom converter, this is the parameter below.

New Retrofit.builder ()                . BaseUrl("http://v.juhe.cn/")                . Addconverterfactory (  Gsonconverterfactory.create ())                . Build ();

For example, we just want the return data to be of type string, we need to customize a converterfactory

 Public classStringconverfactoryextendsConverter.factory { Public Staticstringconverfactory Create () {return Newstringconverfactory (); } @Override PublicConverter<responsebody,?>responsebodyconverter (type type, annotation[] annotations, Retrofit Retrofit) {LOG.D ("Wyz", "Read data: Responsebodyconverter" +type); if(Type = = String.class) {//Type here my understanding is that the call object parameter defines the return value type LOG.D ("Wyz", "Execution Start"); returnstringresponsebodyconverter.instance; }        return NULL; } @Nullable @Override Publicconverter<?, requestbody>requestbodyconverter (type type, annotation[] parameterannotations, annotation[] methodannotations, Retrofit Retrofit) {LOG.D ("Wyz", "Request data type:" +type); if(Type = = Netrequest.class){         }        return NULL; }
 final  class  Stringresponsebodyconverter implements  converter<responsebody, string>< Span style= "COLOR: #000000" > { public   Static  final  stringresponsebodyconverter INSTANCE =new   Stringresponsebodyconverter (); @Override  public  String convert (responsebody value) throws   IOException {log.d (" Wyz "," Convert start: "+ value);        String s  = value.string ();     return   S; }

Finally, the convertfactory is set to the retrofit instance.

New Retrofit.builder ().                baseUrl (base_url).                Client (getokhttpclient ())                . addconverterfactory (stringconverfactory. Create ())

Log:

Finally, the red part is to add a custom client here primarily to intercept the corresponding level of log

There is no log function in retrofit2.0. However, the retrofit2.0 relies on okhttp, so it is possible to implement the actual underlying request and response logs through the interceptor in the Okhttp. Here we need to modify the previous retrofit instance to customize the custom okhttpclient for it. The code is as follows:

Newnew  okhttpclient.builder ()        . Addinterceptor (httplogginginterceptor)         New Retrofit.builder (). Addcalladapterfactory (Rxjavacalladapterfactory.create ())        . Client (okhttpclient)        . BASEURL ("https://api.github.com/")        . Addconverterfactory (Gsonconverterfactory.create ())        . Build ();

Dependencies need to be added:

Compile ' com.squareup.okhttp3:logging-interceptor:3.1.2 '

Effect:

More detailed demo can go to my open source China to see Https://gitee.com/bimingcong/MyRetrofit

Retrofit 2.0 based on okhttp more efficient and faster network framework and custom converters

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.