Retrofit

来源:互联网 发布:淘宝晚班客服兼职 编辑:程序博客网 时间:2024/05/18 17:26

Retrofit

一个可供Android和Java使用的安全的Http框架
javadoc文档,StackOverFlow站点
[toc]

介绍

将http API构造成一个接口

public interface GitHubService {  @GET("users/{user}/repos")  Call<List<Repo>> listRepos(@Path("user") String user);}

retrofit对象来实现上面的接口

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

从service中诞生的call会发起一个异步或者同步的网络请求

Call<List<Repo>> repos = service.listRepos("octocat");

可以用注解来描述一个网络请求:

  • 替换URL参数和支持的查询参数
  • 对象转换为请求体(比如:json,缓冲协议栈)
  • 对个请求体和文件上传

API概述

在接口方法上面的注解说明了应该怎么处理发起的网络请求

请求方法

每一个方法必须有一个HTTP的注解来标明请求方法和相对的URL,这样的注解有五个:GET/POST/PUT/HEAD/DELETE。注解中还可以指定特定的相对URL

@GET("users/list")

你也可以在URL中指定特定的查询参数

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

URL处理

发起请求的URL可以由接口方法参数动态的修改,能够修改的模块被{ 模块 }包围,而接口方法中对应的参数一定被注解@Path(模块)修饰。

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

也能够添加查询的参数

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

复杂的请求参数可以用map来接收

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

请求体

可以用@Body注解来指定一个对象为请求体

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

这个对象会在Retrofit实例中用特定的转换器转换为一个正式的请求体,如果没有在Retrofit中添加转换器,这里只能用@RequestBody注解

表格编码和多个请求体

接口方法同样能够被修饰成以表格编码数据发送和多个对象请求体

当在接口方法上面用@FormUrlEncode注解,则请求体数据会以表单的形式发送出去,每一个键值对使用@Field(key)注解,注解里面的key对应的参数名字,而注解相应的对象则是对应的值

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

当在接口方法上面用@MultiPart注解,可以使用多个对象为请求体(最终合成一个),每个对象用@Part注解修饰

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

多个请求体会在Retrofit中使用对应的转换器,或者它们实现RequestBody去处理他们自己的序列化。

头部处理

使用@Headers注解来设置一个静态的请求头

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

注意请求头不会互相覆盖,请求中会包含所有的请求头,即使多个请求头的名字一样

使用@Header注解能够动态的修改请求头,请求头信息的参数一定要使用@Header注解。如果参数为null,则该请求头会被忽略,否者会将其使用tostring转换成字符串后供使用。

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

如果每一个请求都需要一个相同的特定的请求头,可以使用 OkHttp interceptor 来指定

同步VS.异步

Call实例执行的时候既可以是同步也可以是异步,每一个实例都只能执行一次,但是clone()方法能够复制一份可执行的实例。
在Android中,回调会在主线程中执行,在Java JVM中,回调会在发起请求的线程中执行。

Retrofit配置

Retrofit是一个通过接口方法转换成回调的一个类,Retrofit默认会给一个相对平台稳定的回调,但是也支持自定义

转换器

Retrofit只能将请求体反序列化为OkHttp的RequesBody类型所以接口方法中@Body注解后面也只能用RequestBody类型的参数。
添加转换器后就支持相应的类型了,这里提供了六种常用的序列化模块方便使用

  • 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

下面是一个使用GsonConverterFactory 类生成一个使用Gson反序列化的GitHubService 接口的实例

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

自定义转换器

如果想使用一个Retrofit不支持转换的格式(比如 YAML, txt, 自定义格式等)作为通信数据或者想用一个不同的库来实现已经支持的格式,能够轻松的创建自己的转换器。创建一个类继承 Converter.Factory类,在构建构造器时传递实例。

下载

下载v2.2.0 JAR
Retrofit的源码和使用例子,在GitHub下载

MAVEN

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

GRADLE

compile 'com.squareup.retrofit2:retrofit:2.2.0'

Retrofit至少需要环境版本JAVA7或者Android2.3

PROGUARD
如果你的工程中有使用混淆器,则在你的配置文件中加入下列语句

# Platform calls Class.forName on types which do not exist on Android to determine platform.-dontnote retrofit2.Platform# 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

Retrofit在覆盖下使用Okio,所以你可能也想看一下proguard 规则

贡献

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 the Individual Contributor License Agreement (CLA).

许可证

Copyright 2013 Square, Inc.

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

0 0