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