//首先是依赖
//添加retrofit依赖 compile 'com.squareup.retrofit2:retrofit:2.3.0' //添加gson转换器的依赖 compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile "io.reactivex.rxjava2:rxjava:2.1.10" compile 'io.reactivex.rxjava2:rxandroid:2.0.2' //注意 rxjava2是2.0的 不加2表示的是1.0 compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//代码
public class RestoUtils { private static RestoUtils restoUtils=null; private OkHttpClient okHttpClient; private Retrofit retrofit; public RestoUtils() { } public RestoUtils(String beseurl) { okHttpClient = new OkHttpClient.Builder() .addInterceptor(new CommonParamsInterceptor())//添加拦截器 .connectTimeout(15, TimeUnit.SECONDS)//连接超时 .build(); //创建retrofit retrofit = new Retrofit.Builder() .baseUrl(beseurl) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//设置rxjava,注意是2 .addConverterFactory(GsonConverterFactory.create())//添加gson的转换器 .build(); } /** * 单例模式 */ public static RestoUtils getInstance(String baseurl) { if (restoUtils==null){ synchronized (RestoUtils.class){ if (restoUtils==null){ restoUtils=new RestoUtils(baseurl); } } } return restoUtils; } /** * 封装公共参数的拦截器 */ private static class CommonParamsInterceptor implements Interceptor { //intercept方法就是拦截的意思....拦截的是一个请求,,,一旦拦截之后可以对请求的参数进行处理 //Chain chain 链条的意思 @Override public Response intercept(Chain chain) throws IOException { Log.e("----", "拦截器------"); //调用request()方法得到拦截的请求 Request request = chain.request(); //获取请求的方式 String method = request.method();//GET POST //拦截的请求的路径 String oldUrl = request.url().toString(); //要添加的公共参数...map Map<String, String> map = new HashMap<>(); map.put("source", "android"); if ("GET".equals(method)) { StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder...字符串缓冲区 stringBuilder.append(oldUrl); if (oldUrl.contains("?")) { //?在最后面....2类型 if (oldUrl.indexOf("?") == oldUrl.length() - 1) { } else { //3类型...拼接上& stringBuilder.append("&"); } } else { //不包含? 属于1类型,,,先拼接上?号 stringBuilder.append("?"); } //添加公共参数....source=android&appVersion=100& for (Map.Entry<String, String> entry : map.entrySet()) { //拼接 stringBuilder.append(entry.getKey()) .append("=") .append(entry.getValue()) .append("&"); } //删掉最后一个&符号 if (stringBuilder.indexOf("&") != -1) { stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&")); } //得到含有公共参数的新路径.....使用新路径去请求 String newUrl = stringBuilder.toString(); //新的路径构建一个新的请求 request = request.newBuilder().url(newUrl).build(); } else if ("POST".equals(method)) { Log.e("--oldUrl--", oldUrl); //参数在请求的实体内容上....拿到以前的参数,把以前的参数和公共参数全都添加到请求实体上 RequestBody requestBody = request.body(); if (requestBody instanceof FormBody) {//前边是不是后边的子类/实例对象 FormBody oldBody = (FormBody) requestBody;//keywords...page FormBody.Builder builder = new FormBody.Builder(); //先添加之前的参数 for (int i = 0; i < oldBody.size(); i++) { //键值对的形式添加 builder.add(oldBody.name(i), oldBody.value(i)); } //添加公共参数 for (Map.Entry<String, String> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } //构建一个新的请求 request = request.newBuilder().url(oldUrl).post(builder.build()).build(); } } //执行请求 获取到响应 Response response = chain.proceed(request); return response; } } public <T> T createService(Class<T> service){ return retrofit.create(service); } }
//apiService类
import java.util.Map;
import io.reactivex.Observable;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
public interface ApiService {
/**
* 坑点:--------------路径的字符被转义
*
*/
@GET("{url}")
Observable<ResponseBody> doGetNoParam(@Path(value = "url",encoded = true) String url);
@GET("{url}")
Observable<ResponseBody> doGet(@Path(value = "url",encoded = true) String url, @QueryMap Map<String,String> map);
@FormUrlEncoded
@POST("{url}")
Observable<ResponseBody> doPost(@Path(value = "url",encoded = true) String url, @FieldMap Map<String,String> map);
}