A type-safe Java HTTP Client library retrofit

Source: Internet
Author: User

A type-safe Java HTTP client library Retrofitchszs is not allowed to be reproduced without the permission of the blogger. Permitted reprint should be marked by the Author and blog homepage: Http://blog.csdn.net/chszs, Retrofit introduction

Retrofit is an open source, type-safe HTTP client that works on Android and Java platforms, and the official homepage is:
http://square.github.io/retrofit/

Retrofit requires support for Java 7 or above or Android 2.3 or later.

Second, retrofit dependence

Retrofit's maven dependency:

<dependency><groupId>com.squareup.retrofit2</groupId><artifactId>retrofit</artifactId><version>2.0.0</version></dependency>

Gradle dependencies:

compile ‘com.squareup.retrofit2:retrofit:2.0.0‘
Iii. Retrofit Usage 1, retrofit defines the HTTP service interface Githubservice
public interface GitHubService {    @GET("users/{user}/repos")    Call<List<Repo>> listRepos(@Path("user") String user);}
2. Realization of Githubservice interface generated by retrofit
Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com/")    .build();GitHubService service = retrofit.create(GitHubService.class);

Each call from the Githubservice interface can initiate synchronous or asynchronous requests to the remote server.

Call<List<Repo>> repos = service.listRepos("octocat");
3. Use annotations to describe HTTP requests
    • Support for URL parameter substitution and query parameters
    • object is converted into the requested body
    • The body of the request can be split into multiple parts, supporting file uploads
Iv. API Declaration

The annotations on the interface methods and parameters explain how the request should be handled.

1. Request method

Each method must have an HTTP comment that provides the requested method and the associated URL.
Retrofit built five comments: GET, POST, PUT, DELETE, and HEAD
The associated URL is also specified by the comment.

@GET("users/list")

You can also specify query parameters in the URL.

@GET("users/list?sort=desc")
2. URL manipulation

The requested URL can be dynamically updated--using a block or parameter in the method instead. The substitution block is a string of letters and numbers, surrounded by curly braces {}. The substitution parameters must be annotated with @path, and the string must also be composed of letters and numbers, surrounded by curly braces {}.

@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId);

You can add query parameters

@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

For more complex query parameters, you can use the Map object.

@GET("group/{id}/users")Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
3. Request Body

The body of the HTTP request can be specified using the @body comment.

@POST("users/new")Call<User> createUser(@Body User user);

The retrofit object can be converted using the converter specified by the sample. If you do not add a converter, use only requestbody.

4. Form encoding and multipart

The multipart method can also be declared as data encoded by the form or as data.
@FormEncoded the annotation adornment method, the data that is sent is the data that is encoded by the form. Each key-value pair is decorated with a @field comment.

@FormUrlEncoded@POST("user/edit")Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

The multipart request uses the @multipart annotation to decorate the method, and multiple parts are decorated with @part annotations.

@Multipart@PUT("user/photo")Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
5. Header manipulation

You can use the @headers comment to set a static header for a 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 header content does not overwrite each other, and header content that uses the same name is included in the request.
The requested header can be dynamically updated with the @header annotation, and the corresponding parameters must also be provided in the @header, if the value is Null,header can be omitted. Otherwise, the ToString method is called.

@GET("user")Call<User> getUser(@Header("Authorization") String authorization)

The headers needs to be added to each request and specified by the Okhttp interceptor.

V. Synchronous vs. asynchronous

The call instance can be executed synchronously or asynchronously, with each instance being used only once, but invoking the Clone () method creates a new instance, which is also used by the new instance.
On Android, the main thread executes a callback, whereas in the JVM, a callback occurs on the same thread that executes the HTTP request.

The retrofit class is transformed into a callback object through your hungry API interface.

Six, Converter

By default, retrofit can only deserialize the Responsebody type of HTTP body okhttp, which uses @body to accept requestbody.

You can add converters to support other types. The retrofit offers six converters:

    • 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

The following is an example of an implementation that uses the Gsonconverterfactory class to produce an Githubservice interface, which is deserialized using Gson.

Retrofit retrofit = new Retrofit.Builder()    .baseUrl("https://api.github.com")    .addConverterFactory(GsonConverterFactory.create())    .build();GitHubService service = retrofit.create(GitHubService.class);

A type-safe Java HTTP Client library retrofit

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.