如果大家有需要这个思维导图,可在下面留言,我看到后会分享给你。
前言
什么是retrofit?
官方的回答是:
翻译就是 用于Android和Java的类型安全HTTP客户端。 Rertofit其内部都是支持lambda语法(国内称只链式语法),内部支持okhttp, 并且支持响应式RxJAava,当然jdk1.8 和android studio工具也支持lambda。
Retrofit:
注意需要添加权限
1 基本用法:
首先API接口需要这样写。
public interface GitHubService {
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
}
接着生成一个 GitHubService对象 service
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
然后生成一个Call对象 repos,repos可以进行同步和异步请求
Call> repos = service.listRepos("octocat");
向服务器发起一个请求
repos.enqueue(new Callback()
{
@Override
public void onResponse(Call call, Response response)
{
Log.e(TAG, "getUsePath:" + response.body());
}
@Override
public void onFailure(Call call, Throwable t)
{
}
});
完整的代码:
public interface GitHubService {
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Call> repos = service.listRepos("octocat");
repos.enqueue(new Callback()
{
@Override
public void onResponse(Call call, Response response)
{
Log.e(TAG, "getUsePath:" + response.body());
}
@Override
public void onFailure(Call call, Throwable t)
{
}
});
2 请求方法:
每个方法都必须有一个提供请求方法和相对URL的HTTP注释。有五个内置注释:GET,POST,PUT,DELETE,和HEAD。
@GET (“users / list” )
@GET (“users / list?sort = desc” )//可以指定查询参数
2.1 @Get请求:
可以使用方法上的替换块和参数动态更新请求URL。替换块是由大括号里面的{字母数字字符串}。
@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId);
也可以添加查询参数
@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId, @Query("sort") String sort);
对于复杂的查询参数组合,可以使用Map。
@GET("group/{id}/users")
Call> groupList(@Path("id") int groupId, @QueryMap Map options);
2.2@Post 请求:
基本用法
@POST("users/new")
Call createUser(@Body User user);
表单编码和多个数据:
@FormUrlEncoded
@POST("user/edit")
Call updateUser(@Field("first_name") String first, @Field("last_name") String last);
2.3 Put请求:
@Multipart
@PUT("user/photo")
Call updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
@Multipart 可以用在单文件上传
@PartMap 用于多文件上传
@Multipart
@POST("register")
Call registerUser(@Part MultipartBody.Part photo, @Part("username") RequestBody username, @Part("password") RequestBody password);
@Multipart
@POST("register")
Call registerUser(@PartMap Map params, @Part("password") RequestBody password);
2.4 添加头部:
可以使用@Headers注解为一个方法设置静态头文件。项目需要添加头部就添加,不需要就不添加。
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call> widgetList();
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call getUser(@Path("username") String username);
同步与异步
3 Retrofit转换器
retrofit支持的转换器有以下几个:
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
下面是一个使用Gson的实例,把服务器返回的String类型数据转换为Json对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);
4 Retrofit 下载
jar包:
http://repo1.maven.org/maven2/com/squareup/retrofit2/retrofit/2.3.0/retrofit-2.3.0.jar
MAVEN:
com.squareup.retrofit2
retrofit
2.3.0
Gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
5 混淆 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
http://square.github.io/retrofit/2.x/retrofit/
参考文章: