Retrofit A type-safe HTTP client for Android and Java
2016-06-02 09:20
579 查看
Introduction
Retrofit turns your HTTP API into a Java interface.public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
The
Retrofitclass generates an implementation of the
GitHubServiceinterface.
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build(); GitHubService service = retrofit.create(GitHubService.class);
Each
Callfrom the created
GitHubServicecan make a synchronous or asynchronous HTTP request to the remote webserver.
Call<List<Repo>> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:
URL parameter replacement and query parameter support
Object conversion to request body (e.g., JSON, protocol buffers)
Multipart request body and file upload
Note: This site is still in the process of being expanded for the new 2.0 APIs.
API Declaration
Annotations on the interface methods and its parameters indicate how a request will be handled.Request Method
Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations:GET,
POST,
PUT,
DELETE, and
HEAD. The relative URL of the resource is specified in the annotation.
@GET("users/list")
You can also specify query parameters in the URL.
@GET("users/list?sort=desc")
URL Manipulation
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by{and
}. A corresponding parameter must be annotated with
@Pathusing the same string.
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId);
Query parameters can also be added.
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
For complex query parameter combinations a
Mapcan be used.
@GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
Request Body
An object can be specified for use as an HTTP request body with the@Bodyannotation.
@POST("users/new") Call<User> createUser(@Body User user);
The object will also be converted using a converter specified on the
Retrofitinstance. If no converter is added, only
RequestBodycan be used.
Form Encoded and Multipart
Methods can also be declared to send form-encoded and multipart data.Form-encoded data is sent when
@FormUrlEncodedis present on the method. Each key-value pair is annotated with
@Fieldcontaining 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);
Multipart requests are used when
@Multipartis present on the method. Parts are declared using the
@Partannotation.
@Multipart @PUT("user/photo") Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart parts use one of
Retrofit's converters or they can implement
RequestBodyto handle their own serialization.
Header Manipulation
You can set static headers for a method using the@Headersannotation.
@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 headers do not overwrite each other. All headers with the same name will be included in the request.
A request Header can be updated dynamically using the
@Headerannotation. A corresponding parameter must be provided to the
@Header. If the value is null, the header will be omitted. Otherwise,
toString
will be called on the value, and the result used.
@GET("user") Call<User> getUser(@Header("Authorization") String authorization)
Headers that need to be added to every request can be specified using anOkHttp interceptor.
Synchronous vs. Asynchronous
Callinstances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling
clone()will create a new instance that can be used.
On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.
Retrofit Configuration
Retrofitis the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.
Converters
By default, Retrofit can only deserialize HTTP bodies into OkHttp'sResponseBodytype and it can only accept its
RequestBodytype for
@Body.
Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.
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's an example of using the
GsonConverterFactoryclass to generate an implementation of the
GitHubServiceinterface which uses Gson for its deserialization.
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build(); GitHubService service = retrofit.create(GitHubService.class);
Custom Converters
If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easilycreate your own converter. Create a class that extends the
Converter.Factoryclass and pass in an instance when building your adapter.
Download
↓Latest JARThe source code to the Retrofit, its samples, and this website isavailable on GitHub.
Maven
<dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>(insert latest version)</version> </dependency>
Gradle
compile 'com.squareup.retrofit2:retrofit:(insert latest version)'
Retrofit requires at minimum Java 7 or Android 2.3.
ProGuard
If you are using Proguard in your project add the following lines to your configuration:# Platform calls Class.forName on types which do not exist on Android to determine platform. -dontnote retrofit2.Platform # Platform used when running on RoboVM on iOS. Will not be used at runtime. -dontnote retrofit2.Platform$IOS$MainThreadExecutor # Platform used when running on Java 8 VMs. Will not be 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
Contributing
If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by running
mvn clean verify.
Before your code can be accepted into the project you must also sign theIndividual Contributor License Agreement (CLA).
from:https://github.com/square/retrofit/blob/master/website/index.html
相关文章推荐
- AFN网络请求打印请求失败的错误
- 利用https实现站点的访问
- 利用https实现站点的访问
- 利用https实现站点的访问
- 社交网络中常用数据集
- centos6.7上使用qperf测试网络的带宽和时延!
- iOS开发 - 网络数据安全加密(MD5)
- Java下载网络压缩包及解压
- 网络协议_SNMP协议详解
- Json解析网络数据+listview展示跳转
- xml解析网络请求
- socket网络字节序以及大端序小端序
- TCP四次握手断开连接(图解)
- TCP数据的传输过程
- TCP数据报结构以及三次握手(图解)
- TCP的粘包问题以及数据的无边界性
- debian网络和源设置(新手)
- AnG-顶级的数字营销服务和软件提供商-http://www.agrant.cn
- 转载 https协议和http协议的区别
- Socket网络编程--FTP客户端(60篇socket博客,而且都比较简单、深入浅出)