Retrofit Study 1

Source: Internet
Author: User

The following is an introduction to retrofit from GitHub. In other words, the translation of the Real egg hurts, it took 3 hours fast.

Retrofit An Introduction to the type-safe HTTP client on Android and Java Retrofit can convert your HTTP API to Java interface.  Public InterfaceGithubservice {@GET ("Users/{user}/repos") Call<List<Repo>> Listrepos (@Path ("User") String user); The retrofit class implements the implementation of the Githubservice interface. Retrofit Retrofit=NewRetrofit.builder (). BASEURL ("https://api.github.com"). build (); Githubservice Service= Retrofit.create (Githubservice.class), each call to the created Githubservice can produce a synchronous or asynchronous HTTP request to a remote network server. Pager<List<Repo>> repos = Service.listrepos ("Octocat"); Use annotations to describe HTTP requests:1. Support for URL parameter substitution and query parameters2Request object conversion of body (e.g. JSON, protocol buffers)3. The multipart request body and the File Upload API describe the annotations above the interface method and its parameters that imply how the request is handled. Request method Each method must have an HTTP annotation that provides the request method and the associated URL. Here are five built-in annotations: Get,post,put,delete, and head. The URL of the related resource is specified in the annotation. @GET ("Users/list"You can also specify the parameters of the query in the URL. @GET ("Users/list?sort=desc"URL Action A requested URL can be dynamically updated with parameters in the substitution block and method. An alternative block is an alphanumeric string surrounded by {and}. A matching parameter must be annotated with the @Path of the same string. @GET ("Group/{id}/users") Call<List<User>> grouplist (@Path ("id")intgroupId); You can also add query parameters @get ("Group/{id}/users") Call<List<User>> grouplist (@Path ("id")intGroupId, @Query ("Sort"String sort); complex query parameters can be used with a combined map. @GET ("Group/{id}/users") Call<List<User>> grouplist (@Path ("id")intGROUPID), @QueryMap map<string,string>options); Request block an object can be specified as an HTTP request body@post with @Body annotations ("Users/new") Call<User>createUser (@Body user user), this object can be converted by the retrofit instance specified by the translator converter. If you do not add a translator, only requestbody can be added. The encoding form and the multipart method can be defined to send a form-encoded and multipart data. When @FormUrlEncoded data that appears in encoded form in the method, it can be sent. Each key-value pair is annotated with a @Field that contains the name and the object that provided the value. @FormUrlEncoded @post ("User/edit") Call<User> UpdateUser (@Field ("first_name") String First, @Field ("Last_Name"String last), and the Multipart request can be used when the @Multipart appears in the method. Parts can be declared with @Part annotations. @Multipart @put ("User/photo") Call<User> UpdateUser (@Part ("photo") Requestbody photo, @Part ("description") requestbody description); The multipart section uses a retrofit converter or they can implement requestbody to handle their own serialization. Head operation (header manipulation) You can use @Headers annotations to set static Headers for the method. @Headers ("cache-control:max-age=640000") @GET ("Widget/list") Call<List<Widget>>widgetlist (); @Headers ({"Accept:application/vnd.github.v3.full+json",    "User-agent:retrofit-sample-app"}) @GET ("Users/{username}") Call<User> GetUser (@Path ("username"String username); Note that you cannot override each header. All headers that use the same name will be included in the request. A request header can be updated dynamically using @Header annotations. A matching parameter is required to provide the @Header. If the value is null, the header is omitted. Otherwise, toString will call this value and use this result. @GET ("User") Call<User> GetUser (@Header ("Authorization"String Authorization) The header header that needs to be added to each request can be specified with the Okhttp interceptor Interpolator. Synchronous and asynchronous call instances can be called synchronously or asynchronously. Each instance is only used once, but calling clone () will create a new instance when it is used. In Android, the callback will be executed in the main thread. In the JVM, the callback occurs in the same thread that executes the HTTP request. Retrofit configuration Retrofit is a class that transforms your API interface into callable objects. By default, retrofit will give you a robust default configuration for your platform, but it also allows customization. By default, retrofit can only support the responsebody type of the Body-to-okhttp of the deserialization HTTP, and can only accept its requestbody type with @Body. Converters can be added to support other types. Six modules of the same class can be easily adapted to the popular serialization library. 1.gson:com.squareup.retrofit2:converter-Gson2.jackson:com.squareup.retrofit2:converter-Jackson3.moshi:com.squareup.retrofit2:converter-Protobuf4.wire:com.squareup.retrofit2:converter- Wire5.Simple xml:com.squareup.retrofit2:converter-SimpleXML6.Scalars (Raw primitives, packaged boxed, and string strings): com.squareup.retrofit2:converter-scalars Here is an example using the Gsonconverterfactory class to generate an implementation of the Githubservice interface using the Gson deserialization. Retrofit Retrofit=NewRetrofit.builder (). BASEURL ("https://api.github.com"). Addconverterfactory (Gsonconverterfactory.create ()). build (); Githubservice Service= Retrofit.create (Githubservice.class); custom Converters If you need to communicate with APIs that use retrofit unsupported content formats (such as yaml,txt, custom formats) or if you want to use different libraries to implement an existing format, you can easily create your own converters. Create a class by inheriting the Converter.factory class and upload it to the instance when you build your adapter. MAVEN<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactid>retrofit</ Artifactid> <version> (insert latest Version) </version></dependency>Gradlecompile' Com.squareup.retrofit2:retrofit: (insert latest Version) 'retrofit requires minimal Java7 or Android2.3Confusion If you use the obfuscation in your project, add the following line to your configuration:-dontwarn Retrofit2.**-keepclassretrofit2.** {*; }-keepattributes Signature-keepattributes Exceptionsapache Copyright

Retrofit Study 1

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.