1.创建一个接口,用来定义接口使用的
public interface Api {
@POST("product/getProductDetail")
Observable<Goods_Bean> getGoods(@QueryMap Map<String,String> map);
@POST("product/addCart")
Observable<Add_Bean> getAdd(@QueryMap Map<String,String> map);
@POST("product/getCarts")
Observable<Query_bean> getShopCar(@QueryMap Map<String,String> map);
}
注意导包时要是用的是io包,路径是使用注解的形式,通过Java的反射的机制
2.创建一个拦截器
/**
* 自定义拦截器.使用的是okhttp来定义的拦截器
*/
public class MyInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
HttpUrl httpUrl = request
.url()
.newBuilder()
.addQueryParameter("source", "android")
.build();
Request requestNew = request
.newBuilder()
.url(httpUrl)
.build();
return chain.proceed(requestNew);
}
}
3.创建一个封装类
public class RetrofitUtil {
public static volatile Retrofit instance;
public static Retrofit getInstance(String baseUrl){
if (instance==null){
synchronized (RetrofitUtil.class){
//拦截器
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new MyInterceptor())
.build();
//创建retrofit对象
instance = new Retrofit.Builder()
.baseUrl(baseUrl)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
}
return instance;
}
}