一 依赖
api 'com.squareup.retrofit2:retrofit:2.3.0'
api 'com.squareup.retrofit2:converter-gson:2.3.0' //gson转换器
二 使用
1 建立一个okhttp对象 (使用建造者模式)
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RequestLogInterceptor()) //请求信息打印拦截器
.addInterceptor(new RequestHeaderInterceptor()) //请求头拦截器
.connectTimeout(40L, TimeUnit.SECONDS) //连接超时
.writeTimeout(40L, TimeUnit.SECONDS) //写超时
.readTimeout(40L, TimeUnit.SECONDS) //读超时
.build();
2 创建 retrofit 对象
Retrofit mRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl(baseUrl) //服务器的地址
.addConverterFactory(GsonConverterFactory.create()) //添加gson转换器
.build();
3 定义接口
public interface AuthApi{
@FormUrlEncoded //没有参数的时候不用加
@post("auths/authCode.json")//接口地址
Call<//这里可以对请求返回的结果进行封装> authCode (@FieldMap Map<String,String> params);
}
4 使用泛型方法创建接口
public <T> createApi(Class<T> class){
return mRetrofit.create(class);
}
AuthApi api=createApi(AuthApi.Class);
5 使用
api.authCode .call();//异步请求回调在主线程
网友评论