一、Gradle配置
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
二、使用Retrofit
1.初始化
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://localhost:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
2.编写API
public interface ApiManager {
@GET("URL")
<T> Call<T> request(@Query("name") String name, @Query("password") String pw);
}
3.调用API
ApiManager manager=retrofit.create(ApiManager.class);
Call<T> call=manager.request("admin","123");
call.enqueue(new Callback<T>());//enqueue为异步调用,execute为同步调用
4.API编写示例
/**
* 单个请求参数
*/
@GET("URL")
<T> Call<T> request(@Query("name") String name, @Query("password") String pw);
/**
* 多个请求参数
*/
@GET("URL")
<T> Call<T> request(@QueryMap Map<String, String> map);
/**
* 表单提交
*/
@FormUrlEncoded
@POST("URL")
<T> Call<T> postForm(@FieldMap Map<String, String> map);
/**
* 对象提交
*/
@POST("URL")
<T> Call<T> postBody(@Body Objects objects);
/**
* 单个文件上传
*/
@Multipart
@POST("URL")
Call<RequestBody> uploadFlie(@Part("description") RequestBody description, @Part("files") MultipartBody.Part file);
/**
* 多个文件上传
*/
@Multipart
@POST("{URL}")
<T> Call<T> uploadFiles(@Path("URL") String url, @PartMap() Map<String, RequestBody> maps);
5.取消请求
call.cancel();
三、拦截器
1.Log拦截器
//通过添加网络拦截器的方式来开启Log日志
Retrofit retrofit = new Retrofit.Builder()
.client(new OkHttpClient.Builder()
.addNetworkInterceptor(new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build());
//Level.NONE:关闭日志
//Level.BASIC:基本输出日志
//Level.HEADERS:请求日志
//Level.BODY:主体日志
2.Head拦截器
//多个请求头添加
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request()
.newBuilder()
.addHeader("mac", "f8:00:ea:10:45")
.addHeader("uuid", "gdeflatfgfg5454545e")
.addHeader("netWork", "wifi")
.build();
return chain.proceed(request);
}
})
.build();
//单个请求头添加
@Headers({ "Accept: application/vnd.github.v3.full+json", "User-Agent: Retrofit-your-App"})
@GET("URL")
<T> Call<T> request(@Query("name") String name, @Query("password") String password);