目录:
1、Retrofit接入
2、使用
3、注解

1. Retrofit接入
Retrofit 是Http的一种请求工具,基于OkHttp。
传送门 ✈✈✈ Retrofit Github
传送门 ✈✈✈ Retrofit Website
官方说明:
A type-safe HTTP client for Android and Java
Retrofit支持Android端、Java端和iOS端。
1.1. 配置Gradle
compile 'com.squareup.retrofit2:retrofit:2.2.0'
1.2. 配置Proguard
如果工程中有使用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
2. 使用
2.1. 创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(http://www.baidu.com)
.addConverterFactory(GsonConverterFactory.create())
.build();
2.2. 创建发送请求的接口
public interface LoginApi{
@POST("mobile/login")
Call<ResponseBody> login(@Body LoginPost post);
}
2.3. 发送http请求
发送请求的方式分同步和异步,同步调用Call的.execute()方法,异步调用Call的.enqueue()方法。
public void get() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.baidu.com/").build();
LoginApi api = retrofit.create(LoginApi.class);
Call<ResponseBody> call = api.contributorsBySimpleGetCall(mUserName, mRepo);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//处理请求成功
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
//处理请求失败
}
});
}
3. 注解
Retrofit通过使用注解的方式来简化请求。
注解主要做三种类型的标记:
- 标记请求方式
- 标记请求头
- 标记请求和响应格式
- 标记请求参数
3.1. 标记请求方式
@GET:get请求
@POST:post请求
@PUT:put请求
@DELETE:delete请求
@HEAD:head请求
@OPTIONS:options请求
@PATCH,对PUT请求的补充,用于更新局部资源
@HTTP,通用注解,三个属性:method , path , hasBody
举个栗子:
@GET("mobile/capture")
Call<ResponseBody> getCapture(@Query("phone") String phone);
3.2. 标记请求头
@HEADER:添加不固定请求头,会覆盖原有请求头,作为参数。
@HEADERS:添加固定请求头,支持多个
//使用@HEADER参数
@GET("mobile/active")
Call<ResponseBody> getActive(@Header("token") String token,@Query("id") int activeId);
//使用@Headers添加单个请求头
@Headers("Cache-Control:public,max-age=120")
@GET("mobile/active")
Call<ResponseBody> getActive(@Query("id") int activeId);
//使用@Headers添加多个请求头
@Headers({
"User-Agent:android"
"Cache-Control:public,max-age=120",
})
@GET("mobile/active")
Call<ResponseBody> getActive(@Query("id") int activeId);
3.3. 标记请求和响应格式
@FormUrlEncoded:请求发送表单编码数据,每个键值对使用@Field注解
@Multipart:请求发送multipart数据,配合@Part注解使用
@Streaming:响应用字节流的形式返回
3.4. 标记请求参数
@Body:一般用于Post请求发送非表单数据
@POST("mobile/login")
Call<ResponseBody> login(@Body LoginPost post);
@Field:用于Post请求中表单字段
@POST("mobile/register")
Call<ResponseBody> registerDevice(@Field("id") String registerid);
@FieldMap:同@Field,用于不确定的表单参数
@Part:用于表单字段,适合文件上传
@PartMap:用于表单字段,适合多文件上传
@Query:指定Get参数
@QueryMap:同@Query
@Path:用于Url的占位符
@Url:指定Url路径