okhttp添加自定义拦截器,封装公共请求参数

okhttp 进行网络请求

/**
 * date:2018/11/22
 * author:QMY(QMY)
 * function:
 */
public class OkhttpUtils {
       Handler handler;
      OkHttpClient okHttpClient;

      private static OkhttpUtils mOkhttpUtils;
      //构造方法私有
      private OkhttpUtils() {

          Map map = new HashMap<>();
          map.put("source","android");

          MyInterceptor myInterceptor = new MyInterceptor(map);


          handler = new Handler(Looper.getMainLooper());
          //创建okhttp
           okHttpClient = new OkHttpClient.Builder()
                  .connectTimeout(10, TimeUnit.SECONDS)
                  .readTimeout(10, TimeUnit.SECONDS)
                   .addInterceptor(myInterceptor)
                  .build();
      }

      //单例模式
      public static OkhttpUtils getInstance(){
          if (mOkhttpUtils==null){
              synchronized (OkhttpUtils.class){
                  if (mOkhttpUtils==null){
                      return mOkhttpUtils = new OkhttpUtils();
                  }
              }
          }
          return mOkhttpUtils;
      }

      //接口
      public interface Utils{
          void success(String string);
      }
      //封装doget方法
      public void doGet(String url, final Utils mUtils){
          final Request request = new Request.Builder()
                  .url(url)
                  .build();

          okHttpClient.newCall(request).enqueue(new Callback() {

              @Override
              public void onFailure(okhttp3.Call call, IOException e) {

              }

              @Override
              public void onResponse(okhttp3.Call call, Response response) throws IOException {
                  final String string = response.body().string();
                  handler.post(new Runnable() {
                      @Override
                      public void run() {
                          //接口
                          mUtils.success(string);
                      }
                  });
              }
          });
      }


      //封装doPost
      public void doPost(String url, Map map, final Utils mUtils){
          //formbody
          FormBody.Builder builder = new FormBody.Builder();
          for (String key:map.keySet()){
            builder.add(key,map.get(key));
          }

          FormBody formBody = builder.build();
          final Request request = new Request.Builder()
                  .post(formBody)
                  .url(url)
                  .build();

          okHttpClient.newCall(request).enqueue(new Callback() {

              @Override
              public void onFailure(okhttp3.Call call, IOException e) {

              }

              @Override
              public void onResponse(okhttp3.Call call, Response response) throws IOException {
                  final String string = response.body().string();
                  handler.post(new Runnable() {
                      @Override
                      public void run() {
                          //接口
                          mUtils.success(string);
                      }
                  });
              }
          });
      }

}

自定义拦截器

/**
 * date:2018/11/22
 * author:QMY(QMY)
 * function:自定义一个拦截器,封装公共请求参数
 */
public class MyInterceptor implements Interceptor {

    private final Map map;

    public MyInterceptor(Map map) {
        this.map=map;

    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        //拿到原来的request
        Request oldrequest = chain.request();
        //拿到请求的url
        String url = oldrequest.url().toString();
        //判断是get还是post
        if (oldrequest.method().equalsIgnoreCase("GET")) {
            if (map!=null && map.size()>0){
                StringBuilder stringBuilder = new StringBuilder(url);
                //拼接公共请求参数
                for(Map.Entry entry:map.entrySet()){
                    stringBuilder.append("&"+entry.getKey()+ "=" + entry.getValue());
                }
                url = stringBuilder.toString();
                //如果之前的url没有?号,我们需要手动给他添加一个?号
                if (!url.contains("?")){
                    url = url.replaceFirst("&", "?");
                }
                //依据原来的request构造一个新的request
                Request request = oldrequest.newBuilder()
                        .url(url)
                        .build();

                return chain.proceed(request);

            }else {
                if (map!=null&& map.size()>0){
                    RequestBody body = oldrequest.body();
                    if (body!=null && body instanceof FormBody){
                        FormBody formBody = (FormBody) body;
                        //1.把原来的的body里面的参数添加到新的body中
                        FormBody.Builder builder = new FormBody.Builder();
                        //为了防止重复添加相同的key和value
                        Map temmap = new HashMap<>();
                        for(int i=0;i entry : map.entrySet()) {
                            if(!temmap.containsKey(entry.getKey())){
                                builder.add(entry.getKey(), entry.getValue());
                            }
                        }
                        FormBody newFormBody = builder.build();
                        //依据原来的request构造一个新的request,
                        Request newRequest = oldrequest.newBuilder()
                                .post(newFormBody)
                                .build();
                        return chain.proceed(newRequest);
                    }
                }
            }
        }

        return chain.proceed(oldrequest);
    }
}

你可能感兴趣的:(okhttp添加自定义拦截器,封装公共请求参数)