Retrofit detailed use

Source: Internet
Author: User
Tags http request serialization sort alphanumeric characters

Retrofit2.0 Project homepage
RETROFIT2.0 Official Document Introduction

Retrofit is a type-safe HTTP client for Android and Java, produced by Square, based on the Okhttp Network service.
RETROFIT2.0: The biggest improvement ever made using Retrofit2.0

Download V2.0.0-beta2 JAR Gradle:

Compile ' com.squareup.retrofit:retrofit:2.0.0-beta2 '
1 1 Maven:
<dependency>
  <groupId>com.squareup.retrofit</groupId>
  <artifactId>retrofit< /artifactid>
  <version>2.0.0-beta2</version>
</dependency>
1 2 3) 4 5
1 2 3 4 5 Usage Introduction

Convert HTTP API to Java interface

Public interface Githubservice {
  @GET ("Users/{user}/repos")
  call<list<repo>> Listrepos (@Path ("User") String user);
1 2 3 4
1 2 3 4

Implementation of generating interface Githubservice using class retrofit

Retrofit Retrofit = new Retrofit.builder ()
    . BASEURL ("https://api.github.com/")
    . Build ();

Githubservice service = retrofit.create (Githubservice.class);
1 2 3) 4 5
1 2 3) 4 5

You can then directly invoke the generated Githubservcie instance to send a synchronous or asynchronous request to the Web server

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

* BaseURL and annotations in URL-connected "/" should preferably be written in the back of BaseURL, rather than in front of the URL in the annotation, otherwise unpredictable errors may occur. * API Declaration

The annotations and parameters of the interface function indicate how to handle the request request method

Each function must have HTTP annotations that provide the request and relative URLs, and retrofit provides 5 built-in annotations: GET, POST, PUT, delete, and head, the relative URL of the resource specified in the annotation

@GET ("Users/list")
1
1

You can also specify query parameters in the URL

@GET ("Users/list?sort=desc")
1
1 URL Handling

The requested URL can be dynamically updated with substitution blocks and parameters in the function, the replacement block is a string of alphanumeric characters surrounded by {and}, and the corresponding argument must be annotated with the same string by @path

@GET ("Group/{id}/users")
list<user> grouplist (@Path ("id") int groupId);
1 2
1 2

You can also add query parameters

@GET ("Group/{id}/users")
list<user> grouplist (@Path ("id") int groupId, @Query ("sort") String sort);
1 2
1 2

Complex query parameters can be combined using a map

@GET ("Group/{id}/users")
list<user> grouplist (@Path ("id") int groupId, @QueryMap map<string, string> Options);
1 2
1 2 request Body

You can specify an object as the request body for an HTTP request through the @body annotation

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

The object will be converted by the converter specified by the Retroofit instance, and if no converter is added, only requestbody is available. (the addition of converters is described later) FORM encoded and MULTIPART

Functions can also be declared to send form-encoded and multipart data.
When the function has @formurlencoded annotations, the form-encoded data is sent, each key-value pair is annotated with the @field annotation containing the name and the object providing the value.

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

When the function has @multipart annotations, the multipart data is sent, and parts is declared using @part annotations.

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

Multipart parts to use one of retrofit's many converters or implement Requestbody to handle its own serialization. Header Processing

You can use @headers annotations to set a static header for a function

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

It is important to note that headers cannot be overwritten with each other. All headers with the same name will be included in the request.

You can use the @header annotation to dynamically update a requested header. The @header must be given the appropriate parameters, if the value of the argument is NULL header will be ignored, otherwise call the parameter value of the ToString () method and use the return result

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

Use the Okhttp interceptor to specify the required header for each HTTP request

Okhttpclient client = new Okhttpclient ();
Client.networkinterceptors (). Add (New Interceptor () {
    @Override public
    com.squareup.okhttp.Response Intercept (Chain Chain) throws IOException {

        Com.squareup.okhttp.Response Response = Chain.proceed (Chain.request () );

        Do anything with response here

        return response;
    }
);
Retrofit Retrofit = new Retrofit.builder ()
        . BASEURL (base_url) ...
        . Client (client)
        . Build ();
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 All in one, synchronous VS asynchronous

Each call instance can be executed synchronously (Call.excute ()) or asynchronously (Call.enquene (callback<?> CallBack)), and each instance can be used only once, but the clone () function to create a new, available instance.
You can also use callback to define an asynchronous method:

@GET ("User/{id}/photo")
void Getuserphoto (@Path ("id") int ID, callback<photo> CB);
1 2
1 2

On Android, the callback is executed on the main thread; on the JVM, the callback is executed on the thread that sent the HTTP request. Retrofit Configuration

The retrofit is a callable object that is converted through the API interface, which has a reasonable configuration and can be customized by default. Converters

By default, retrofit can only deserialize the responsebody type of the HTTP body as Okhttp, and can only accept parameters of the Responsebody type as @body.
Add converters can support other types, retrofit provides six sibling modules for easy adaptation to popular serialization libraries: 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 Custom Converters

You can easily create your own converters if you need to use retrofit to communicate in an out-of-the-box content format (such as YAML, TXT, custom format) and APIs, or if you want to use a different library to implement a format that already exists. How to create: Creates a new class that inherits the Converter.factory class and passes in the converter instance when the retrofit instance is built.

Retrofit Retrofit = new Retrofit.builder ()
        . BASEURL (Base_url)
        . Addcalladapterfactory ( Rxjavacalladapterfactory.create ())//Use Rxjava as the callback adapter
        . Addconverterfactory (Gsonconverterfactory.create ())// Use Gson as the data converter
        . Build ();
1 2 3) 4 5
1 2 3) 4 5

Using Rxjava and Gson converters requires adding dependencies

Retrofit adapter Rxjava
compile ' com.squareup.retrofit:adapter-rxjava:2.0.0-beta1 '
//Retrofit Gson Data Converter
Compile ' com.squareup.retrofit:converter-gson:2.0.0-beta1 '
1 2 3 4
1 2 3 4 for use with Rxjava

Under Rxjava, you can define an asynchronous function with observable:

@GET ("User/{id}/photo")
observable<photo> Getuserphoto (@Path ("id") int id);
1 2
1 2

Now you can do a lot of things, not only to get the data but also to change the data.
Retrofit support for observable makes it easy to combine multiple rest calls together. For example, we have a call to get a photo, a second call to get the native data, and we can package the results together.

Observable.zip (
    Service.getuserphoto (ID),
    service.getphotometadata (ID),
    (photo, metadata), Createphotowithdata (photo, metadata))
    . Subscribe (Photowithdata-Showphoto (Photowithdata));
1 2 3) 4 5
1 2 3) 4 5

Rxjava + Retrofit makes it easier to combine multiple rest calls into one.

Rxjava Project homepage
Rxandroid Project Home RxJava Tutorial: RxJava for Android developers RxJava (i: Basic) Easy to RxJava (ii: operator) in Layman's RxJava three – the benefits of responsiveness In layman's Rxjava four-using responsive programming retrofit code obfuscation configuration in Android

-dontwarn retrofit.**
-keep class retrofit.** {*;}
-keepattributes Signature
-keepattributes Exceptions
1 2 3) 4 5
1 2 3) 4 5

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.