Use of retrofit (1)

Source: Internet
Author: User

This article is not original, but probably translated Retrofit English documents, right as their own notes only.

English Original address: http://square.github.io/retrofit/

1. Introduction

Retrofit Convert your HTTP API to a Java interface.

1  Public Interface Githubservice {2   @GET ("/users/{user}/repos")3   Call<list<repo >> Listrepos (@Path ("user") String user); 4 }

Retrofit generates an implementation class for the Githubservice interface.

1 New Retrofit.builder () 2     . BASEURL ("https://api.github.com")3    . Build (); 4 5 Githubservice service = retrofit.create (githubservice.  Class);

  

  Each call from the generated githubservice can issue a synchronous or asynchronous HTTP request to the remote Web server.

1 call<list<repo>> repos = Service.listrepos ("Octocat");

Use annotations to describe HTTP requests:

    • Support for URL parameter substitution and request parameters
    • Support object to request body (E.g.,json, protocol buffers)
    • Supports multiple request body and file uploads
Statement of the 2.API

The Annotations and its parameters on the interface method indicate how the request is handled.

  

A. Request method

Each method must have an HTTP annotation that provides the request method and the Releative URL. Retrofit contains five types of annotations:,,, GET POST PUT DELETE , and HEAD。在 annotation 中资源的  relative URLs are specified.

1 @GET ("/users/list")

You can also specify the request parameters in the URL.

1 @GET ("/users/list?sort=desc")

B.url processing

A request URL can be dynamically replaced by a replacement block and a parameter on the method. Replacement block is a string containing letters or numbers wrapped by "{}". The corresponding parameter must be a string with the same @Path. That

1 @GET ("/group/{id}/users")2int groupId);

The parameters of the query can also be added.

1 @GET ("/group/{id}/users")2int groupId, @Query ("sort"), String sort);

For complex query parameters can be combined into a Map to use.

1 @GET ("/group/{id}/users")2int groupId, @QueryMap map<string, string> Options);

C. Request body

An object with @Body annotations can be used as the request body for HTTP.

1 @POST ("/users/new")2 call<user> createUser (@Body user user);

This object can be converted by Retrofit the specified converter. If not specified, only requestbody can be used.

  

D.form encoded and Multipart

Methods can also be declared to send form-encoded and mutipart data.

When using form-encoded, add an @ annotation to the Method FormUrlEncoded . Each key value pair uses the @ Field annotation package key. That

1 @FormUrlEncoded 2 @POST ("/user/edit")3 call<user> updateUser (@Field ("first_name") String First, @ Field ("last_name") String last);

To add a @ on a Method when using multiple requestsMultipart 注解,每部分使用 @Part 添加声明。即:

1 @Multipart 2 @PUT ("/user/photo")3 call<user> updateUser (@Part ("photo") Requestbody photo, @ Part ("description") requestbody description);

Multiple requests partially use Retrofit 的转换器或者 their own implementations RequestBody to handle their own serialization.

  

E. Manipulation of the request head

You can use @ Headers to set a static request header for a request method.

1 @Headers ("cache-control:max-age=640000")2 @GET ("/widget/list")3 Call<list<widget>> widgetlist ();
1 @Headers ({2     "Accept:application/vnd.github.v3.full+json",3     " User-agent:retrofit-sample-app "4})5 @GET ("/users/{username} ")6 call<user> GetUser (@Path ("username") String username);

Note that all Headers will not be rewritten, and all Headers with the same name will be included in the request.

The Headers of a request can be updated dynamically using @Headers annotations. You must set a letter or a number parameter for the @Headers. If the true value is null, the request header is ignored, otherwise the toString () method is called and is used in the request.

1 @GET ("/user")2 call<user> getUser (@Header ("Authorization") String Authorization)

Headers that need to being added to every the request can be specified using an OkHttp interceptor.

F. Sync VS. Asynchronous

The call instance can be executed synchronously or asynchronously. Each instance can be used only once, but if you use the Clone () method, you can create another instance that you can use.

In Android, callbacks are executed in the main thread. Callbacks in the JVM are executed in the same thread that initiated the HTTP request.

3.Retrofit parameter Configuration

Retrofit is a class that is converted to a callback object through your API interface. Retrofit provides you with a default configuration, but it also allows you to customize the configuration.

A. Converters

By default, Retrofit can only speak the responebody type that HTTP bodies is serialized to OkHttp, and can only receive responebody types for @Body.

Converters can also support the following types:

    • Gson:com.squareup.retrofit:converter-gson
    • Jackson:com.squareup.retrofit:converter-jackson
    • Moshi:com.squareup.retrofit:converter-moshi
    • PROTOBUF:com.squareup.retrofit:converter-protobuf
    • Wire:com.squareup.retrofit:converter-wire
    • Simple XML:com.squareup.retrofit:converter-simplexml

B. Custom Converters

You can also pass Converter.Factory the class custom converter by inheriting it, and then create the adapter to pass in the instance.

4. Integration method

For the latest jar package, please click here.

Retrofit Source code and sample program on Github.

Maven

<Dependency>  <groupId>Com.squareup.retrofit</groupId>  <Artifactid>Retrofit</Artifactid>  <version>(insert latest Version)</version></Dependency>

Gradle

Compile ' Com.squareup.retrofit:retrofit: (insert latest Version) '

Retrofit needs the environment: more than 7 Java and Android 2.3.

Proguard

1 -dontwarn retrofit.**2class retrofit.** {*;} 3 -keepattributes Signature4 -keepattributes Exceptions

  

Retrofit use (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.