引入库:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
使用方式:
1.不带参数get请求:
@GET("path")
Observable<BaseBean> getData();
2.带参数get请求:
@GET("path")
Observable<BaseBean> getData(@Query("id") int id);
3.url带参数get请求:
@GET("dynamic/comment/{userName}/comment")
Observable<BaseBean> getData(@Path("userName") String userName);
4.不带参数post请求:
@POST("path")
Observable<BaseBean> getData();
5.带参数post请求:需加入FormUrlEncoded注解
@FormUrlEncoded
@POST("path")
Observable<BaseBean> getData(@Field("userId") String userId,@Field("videoId") String videoId);
6.带header的post请求:
@FormUrlEncoded
@Headers("token:eyJhbGciOiJSUzI1NiVzZXIiLCJhdWQiOiJ7mI44kkb3t3jVDzxfwGRFjKSIKVNZCS5VuA")
@POST("path")
Observable<BaseBean> getData(@Field("userId") String userId);
6.put请求,需要添加@FormUrlEncoded注解
@FormUrlEncoded
@PUT("path")
Observable<BaseBean> getData();
7.delete请求:
@DELETE("path")
Observable<TipsBean> logout(@Query("id") String userId);
8.patch请求
@PATCH("path")
Observable<TipsBean> unBindThird(@Query("type") String type);
设置统一header:
public class HeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
if (UserInfoCache.TOKEN != null) {
builder.addHeader(TOKEN, UserInfoCache.TOKEN);
}
return chain.proceed(builder.build());
}
}
在OkHttpClient创建时添加这个header拦截器
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addInterceptor(new HeaderInterceptor()); //添加header
Retrofit使用创建:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
注:
- 默认情况只能将请求结果转化为ResponseBody
需要转为自定义的Bean类,需要添加
.addConverterFactory(GsonConverterFactory.create())
否则,会报转化不合法异常。
- 默认情况返回Call,要返回Observable需要添加
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())。