Retrofit2 Re-study

Source: Internet
Author: User

Retrofit2 re-study and comparison with volley 1. Features
  • retrofit2.Call<T>

    Represents a call to a method that sends a request to the server and returns the corresponding result, which can be canceled, can be synchronously requested, or can be requested asynchronously. Similar to the requestqueue in volley. It is type-safe, each call can only be adjusted once, request and response are one by one corresponding, through clone can execute the same request.

  • Pluggable serialization Mechanisms:

    Many protocols have been implemented, including JSON,JACKSON,XML,PROROBUF and so on, and it is easy to customize, just implement the converter interface. A rest adapter can bind multiple converter, and the policy that takes the query determines which converter to use.

    Note: Because JSON does not have any inheritance constraints. So we cannot determine by what exact condition an object is a JSON object. So that JSON's converters will reply to any data: I can handle it! This must remember that the JSON converter must be put in the end, or it will not match your expectations

  • Flexible Calladapter, implementing a replaceable execution mechanism that can adapt call to any type you need:

    Simply put, you can customize the return type of the service interface by implementing Calladapter, which by default is Call<T> the existing implementation:

    • Rxjava-adapter (Fit observable)
    • Guava-adapter (Fit Listenablefuture)
    • Java8-adapter (Fit Completablefuture)

    It is important to note that the Execute () or Equeue () method of call is automatically invoked internally by these three implementations.

  • Parameterized Response object:Response<T>

    The response holds the converted object. The return data of type T can be obtained by Response.body (). The Response object also contains some important metadata: The response code (the Reponse Code), the response message (the Response message), and the response header (headers).

  • Post request can be passed as an object parameter
    @POST("users/new")Call<User> createUser(@Body User user);
  • @Url, allows direct pass-through of a requested URL:

    Example:

    interface GitHubService {@GET("/repos/{owner}/{repo}/contributors")Call<List<Contributor>> repoContributors(  @Path("owner") String owner,  @Path("repo") String repo);@GETCall<List<Contributor>> repoContributorsPaginate(  @Url String url);}
  • Absolute address and relative address

    The service interface method is requested in the annotation, "/" begins as an absolute address, when the full URL is generated, it is followed by the host, otherwise the relative address, followed by BaseURL.

  • resolve the response header, to achieve continuous requests, is to smooth

    Example:
    Parse paging data in request header for paging

    response<list<contributor>> Response = Call.execute (); //http/1.1 OK  //Link:  Page=2  >; Rel= "Next" , //api.github.com/repositories /892275/ contributors?page=3  >; Rel= "last"  //...  String links = response.headers (). Get ( "Link" ); String NextLink = nextfromgithublinks (links); //https://api.github.com/repositories/892275/contributors?page=2  Call<list<contributor>> nextcall =githubservice.repocontributorspaginate (nextLink);  
  • Integrates with the excellent APIs already in okhttp to reduce the volume of retrofit 2

    OkHttp is now small and focused, with a lot of good API interfaces. In Retrofit 2, there are interface mappings to OkHttp, as well as all the features we need to compress the Retrofit library size. We finally reduced the volume of retrofit 60% (only 85k), while also having more features.

  • Okio

    The implementation of Okhttp uses a high-performance IO library Okio

  • Interception device

    Through the configuration of interceptors, the implementation of the log, add decryption, dynamic addition of headers, modify the request (URL) and other functions.
    mechanism:
    Interceptor 1-> Interceptor 2-> Interceptor 3-> Interceptor N-> Request Server via Httpengine, return response
    Interceptor N->...-> Interceptor 3-> Interceptor 2-> Interceptor 1-> response

  • Timeout mechanism

    OkHttp has a default timeout mechanism, and if you don't need to customize it, you don't actually have to make any settings.

  • Error Body converter
    //look up a converter for the Error type on the Retrofit instance.  Converter<responsebody, error> errorconverter = Retrofit.responsebodyconverter (Error.class, new  annotation[0 ]); //Convert the error body into our error type.  Error Error = Errorconverter.convert (Response.errorbody ()); System.out.println ( "ERROR:"  + error.message);  
  • can customize Gson objects, set Typeadapter, etc.

    Example

    gson Gson = new  gsonbuilder (). Setdateformat (" Yyyy-mm-dd ' T ' HH:mm:ssZ "). Create (); Retrofit Retrofit = new  retrofit.builder (). BASEURL ("). Addconverterfactory (Gsonconverterfactory.create (Gson)). build (); service = Retrofit.create (Apiservice.class);  
  • Response parsing failure case

    On Retrofit 1.9, if the fetched response couldn ' t is parsed into the defined Object, failure would be called. But in Retrofit 2.0, whether the response is being able to parse or not, onresponse'll be always called. The case the result couldn ' t is parsed into the Object, Response.body () would return as null. Don ' t forget to handle.

  • Certificate pinning (certificate chain)

    Https Certificate
    HSTS: HTTP Strict Transport Security

  • Mock response

    OkHttp provides mockwebserver extension, which can be used for local debugging.

  • Backwards compatibility

    2.0 later to take a new version of the strategy, the large version slow slow, the package name with the version number, Artifactid with the version number.

  • Implementation

    By Call stack order:
    adapt-Adapter

    call Service method->servicemethod.calladapter.adapt (okhttpcall);  

    Retrofit2. Call.execute ()
    Executes the call method, sends a request
    convert-conversion

    retrofit2. Okhttpcall.execute ()->parseresponse (Rawcall.execute ())  

    rawcall.execute ()-Execute

    OKHTTP3. Realcall.execute ()  

    intercept-intercept

    sendrequest-request

    applicationinterceptorchain.proceed () //in Realcall class   

    Sequencing: Fit-execute-intercept-request-intercept-convert

  • Proguard

    -dontwarn retrofit2.**
    -keep class Retrofit2. * { ; }
    -keepattributes Signature
    -keepattributes Exceptions

Volley vs Retrofit2
Features Volley Retrofit2
Upload
Download X
Synchronous
Request priority X
Retry
Encapsulation and extensibility Excellent Liang
Ease of Use Liang Excellent
Response String/iamge/jsonobject Object
Header operation
Document Less Many
Jar Package Size 92k 75D
Api Less Rich
Boilerplate code Many Less
Okhttp
Http Cache
Okhttp
Dynamic URLs
Restful Api X
Interception device X
Rxjava/guava/java8 X
Version update Slow (Stopped more) Fast
Latest Version 1.0.19 (2015/9) 2.0.2 (2016/4/11)
Platform Android Java/android
Restful API can support has supported

about retrofit Basic Packaging solutions:
Https://github.com/simplify20/RetrofitDemos
Reference:
https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/
https://inthecheesefactory.com/blog/retrofit-2.0/en
http://riggaroo.co.za/retrofit-2-mocking-http-responses/
http://vickychijwani.me/retrofit-vs-volley/
http://stackoverflow.com/questions/29119253/retrofit-okhttp-client-how-to-cache-the-response/31097050# 31097050https://github.com/square/retrofit/issues/820
http://stackoverflow.com/questions/32579754/retrying-the-request-using-retrofit-2/32840088#32840088

Retrofit2 Re-study

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.