Android Open Source Network framework retrofit (Getting started) __android

Source: Internet
Author: User
Tags serialization

RESTful style interface has become the mainstream of the industry, retrofit framework also fire special fire, the recent project also decided to upgrade, the use of retrofit. In the spirit of learning, but also to the next learners have some help, so wrote this article, the main content of the official website of the content of a translation and supplementary explanations.
Plus: This article assumes that you know something about the basic HTTP protocol. Introduction of Retrofit

Retrofit internal use of Okhttp for network requests, will transform the network request into a Java interface, using the compile-time annotation to improve the development efficiency. For example, in development, define a network request in a specialized Java interface

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

Generate an implementation for this interface through retrofit, the code is as follows

Custom Okhttpclient
okhttpclient okhttpclient = new Okhttpclient.builder ()
                . ReadTimeout (Default_timeout_ms, Timeunit.milliseconds)
                . ConnectTimeout (Default_timeout_ms, Timeunit.milliseconds)
                . WriteTimeout (DEFAULT _timeout_ms, Timeunit.milliseconds)
                . Build ();

Instantiate retrofit
RETROFIT RETROFIT = new Retrofit.builder ()
    . BaseURL ("https://api.github.com/")
     . Client ( okhttpclient)
    . Build ();


Generate implementation class
Githubservice service = retrofit.create (Githubservice.class);

With the generated githubservice, developers can request a network interface in either synchronous or asynchronous way.

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

Retrofit uses annotations to describe HTTP interfaces and improves development efficiency, which has the following characteristics: URL parameter dynamic substitution, dynamic address bar parameters. objects can be dynamically converted into requestbody, such as JSON and protocol buffers. Support multipart Requestbody (for this not understand, read this blog) support file upload.

The above characteristics, the specific look at the section below to understand. Second, the retrofit annotation usage detailed explanation 1. Statement of network Interface

In retrofit, each network interface must have an annotation, and the annotations on the network interface indicate the type, URL access path. Here are five built-in annotations: Get, POST, put, DELETE, and head. The following example declares a simple get network interface with a relative path of users/list.

@GET ("Users/list")

As with tradition, you can add parameters to the path.

@GET ("Users/list?sort=desc")
2. URL-related annotations

A relative path can declare a dynamic parameter, represented by the {STR1} code, that modifies the corresponding parameter for dynamic substitution in the interface by @Path ("str1").

The specific usage is shown below, where the value of GroupID dynamically replaces {ID} in the access path.

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

The Address bar parameter can also be added by using the @Query ("str"), which is the effect of dynamically adding @Query ("str") identification after the access URL

The final URL would be this way, as follows: Group/{id}/users/?sort=xxx

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

If you want to add a lot of address bar parameters, retrofit provides the way map, multiple key value pairs in the map will be added to the URL in turn.

@GET ("Group/{id}/users")
call<list<user>> grouplist (@Path ("id") int groupId, @QueryMap map< String, string> options);
3. Request Body Related annotation

As mentioned above, objects can be dynamically converted into requestbody, specifically to use @Body annotations before an object. As the following code shows, the user object is converted to body.

@POST ("Users/new")
call<user> createuser (@Body user user);

The object would also be converted using a converter specified on the retrofit instance. If No converter is added, only requestbody can be used.

The way objects are converted to body is a retrofit by default, and you can create a converter yourself to specify when retrofit is instantiated. 4. Forms and use multipart body

Retrofit uses the annotation @FormUrlEncoded to indicate that the form is used, and the corresponding fields in the form are identified with the @Field ("XXX") before the interface parameters, and the key values are inside the brackets.

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

The Multipart body is directly used @Multipart identified on the interface method. The parts in the body uses the @Part identity directly.

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

As stated above, Multipart parts also uses the retrofit default serialization converter, and if you want to define serialization yourself, you can inherit the Requestbody class and rewrite the serialization method. 5. Retrofit set up the request header's related annotation

You can set the request header field for some methods, using the @Headers annotation

@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);

The Request header field can also be changed dynamically, adding @Header to the interface parameters.

Extra NOTE: If this parameter is passed to null, the field of the request header is deleted. The parameter type of the field can be not a string type, retrofit eventually calls the ToString () method of the parameter, and the resulting value is the value of the field in the request header.

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

Looking down, maybe some readers will ask, do I need to set the request header for each interface method.

No, the request headers to be used for all interfaces can be set uniformly by the Okhttp interceptor. iii. configuration of retrofit

Through the above description, we should have found that the function of retrofit is to turn the network request into a callable instance object, which is the restful style of each network request interface. Retrofit provides some good annotations to help ease the work of encapsulating network modules.

Retrofit defaults to provide the right, robust default configuration for our platform, but we can also customize these configurations.

By default, retrofit can only deserialize the HTTP body type into a okhttp responsebody type, and the interface defaults to the Requestbody type, as described above.

Retrofit support to configure other converters to support other types, the official website offers the following 6 dynamically configurable libraries, which you need to configure in Gradle. 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

Here is an example of how to use the other converters, which only need to be dynamically passed in to the converter when creating the retrofit object. The following example uses the Gson as a deserialization tool.

Retrofit RETROFIT = new Retrofit.builder ()
    . BaseURL ("https://api.github.com")
    . Addconverterfactory ( Gsonconverterfactory.create ())
    . Build ();

Githubservice service = retrofit.create (Githubservice.class);

If the converter provided by the official website cannot satisfy you, you can inherit the Converter.factory class yourself, extend the function you need to use retrofit 1. Gradle Configuration

Compile ' com.squareup.retrofit2:retrofit:2.1.0 '

Note: Retrofit supports only Java 7 and Android 2.3 versions. 2. Proguard Configuration

If your project uses confusion, add the following code to the Proguards-rules folder.

# Platform calls Class.forName on types which don't exist on Android to determine Platform.
-dontnote Retrofit2. Platform
# Platform used when running on ROBOVM on IOS. Won't is used at runtime.
-dontnote Retrofit2. Platform$ios$mainthreadexecutor
# Platform used when running on Java 8 VMs. Won't is used at runtime.
-dontwarn Retrofit2. Platform$java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes exceptions

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.