OkHttp3中Interceptor的使用心得

作者: HitenDev | 来源:发表于2016-11-23 14:43 被阅读1257次

    在看到这篇文章时,希望你已经阅读过OkHttp对Interceptor的正式介绍,地址在这里,同时,你还可以知道okhttp-logging-interceptor这个辅助库,当然如果你没有阅读过也并无大碍,这篇文章重在描述使用场景和个人心得;

    在去年网上讨论最多的就是OkHttp和Volley的比较,我当时决定把项目中的Volley换成OkHttp2,是因为在弱网环境下测试,OkHttp比较坚强,所以就用它了,并不是对Square的情怀;在一年多的使用中,不论是从2.x版本升到3.x,OkHttp绝对是最好用的库,特别是加之Retrofit,如虎添翼;

    这篇文章是讲Interceptor的使用心得,这就根据我所用,总结出这么几点:

    • Log输出
    • 增加公共请求参数
    • 修改请求头
    • 加密请求参数
    • 服务器端错误码处理(时间戳异常为例)

    这几点绝不是全面,但至少是目前很多开发者或多或少都会遇到的问题,Log输出是必须有的,公共参数这是必须有的,请求头加密和参数加密,这个不一定都有;重点是服务端错误码处理,这个放在哪里处理,见仁见智,但是有些比较恶心的错误,比如时间戳异常(请求任何一个服务器接口时必须携带时间戳参数,服务器专门有提供时间戳的接口,这个时间戳要和服务器时间戳同步,容错在5秒,否则就返回时间戳错误),比如客户端修改系统时间时这一刻又断网了,监听时间变化也没用,又不可能定时去获取,所以何时需要同步,去请求这个接口成了问题,我处理的方案是在Interceptor中过滤结果,当某个接口返回时间戳异常时,不把结果往上返,再执行一次时间戳接口,如果获取成功,传入参数并重构之前的请求,如果获取失败,把之前时间戳异常的接果返回。

    说了这几条,其实具体实现要回归到Interceptor这个类
    我们要实现:

    • 解析出来请求参数
    • 对请求进行重构
    • 解析出Response结果
    • 重构Response

    首先,Log输出可以直接使用官方的https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
    这只有一个类,我这篇文章解析Response的核心代码其实是参考了这个库;

    我们自己来做,第一步,就要实现Interceptor接口,重写Response intercept(Chain chain)方法

    @Overridepublic Response intercept(Chain chain) throws IOException {   
       Request request = chain.request();   
       request = handlerRequest(request);    
       if (request == null) {       
       throw new RuntimeException("Request返回值不能为空");  
       }    
        Response response = handlerRespose(chain.proceed(request), chain);   
        if (response==null){  
           throw new RuntimeException("Response返回值不能为空");
        } 
       return response;}
    

    如何解析出请求参数

            /**
             * 解析请求参数
             * @param request
             * @return
             */
            public static Map<String, String> parseParams(Request request) {
                //GET POST DELETE PUT PATCH
                String method = request.method();
                Map<String, String> params = null;
                if ("GET".equals(method)) {
                    params = doGet(request);
                } else if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || "PATCH".equals(method)) {
                    RequestBody body = request.body();
                    if (body != null && body instanceof FormBody) {
                        params = doForm(request);
                    }
                }
                return params;
            }
             /**
             * 获取get方式的请求参数
             * @param request
             * @return
             */
            private static Map<String, String> doGet(Request request) {
                Map<String, String> params = null;
                HttpUrl url = request.url();
                Set<String> strings = url.queryParameterNames();
                if (strings != null) {
                    Iterator<String> iterator = strings.iterator();
                    params = new HashMap<>();
                    int i = 0;
                    while (iterator.hasNext()) {
                        String name = iterator.next();
                        String value = url.queryParameterValue(i);
                        params.put(name, value);
                        i++;
                    }
                }
                return params;
            }
    
            /**
             * 获取表单的请求参数
             * @param request
             * @return
             */
            private static Map<String, String> doForm(Request request) {
                Map<String, String> params = null;
                FormBody body = null;
                try {
                    body = (FormBody) request.body();
                } catch (ClassCastException c) {
                }
                if (body != null) {
                    int size = body.size();
                    if (size > 0) {
                        params = new HashMap<>();
                        for (int i = 0; i < size; i++) {
                            params.put(body.name(i), body.value(i));
                        }
                    }
                }
                return params;
            }
    }
    
    

    解析参数就是判断请求类型,get类型是从url解析参数,其他类型是从FormBody取,可以上传文件的表单请求暂时没有考虑进来;

    重构Request增加公共参数

      @Override
        public Request handlerRequest(Request request) {
            Map<String, String> params = parseParams(Request);
            if (params == null) {
                params = new HashMap<>();
            }
            //这里为公共的参数
            params.put("common", "value");
            params.put("timeToken", String.valueOf(TimeToken.TIME_TOKEN));
            String method = request.method();
            if ("GET".equals(method)) {
                StringBuilder sb = new StringBuilder(customRequest.noQueryUrl);
                sb.append("?").append(UrlUtil.map2QueryStr(params));
                return request.newBuilder().url(sb.toString()).build();
            } else if ("POST".equals(method) || "PUT".equals(method) || "DELETE".equals(method) || "PATCH".equals(method)) {
                if (request.body() instanceof FormBody) {
                    FormBody.Builder bodyBuilder = new FormBody.Builder();
                    Iterator<Map.Entry<String, String>> entryIterator = params.entrySet().iterator();
                    while (entryIterator.hasNext()) {
                        String key = entryIterator.next().getKey();
                        String value = entryIterator.next().getValue();
                        bodyBuilder.add(key, value);
                    }
                    return request.newBuilder().method(method, bodyBuilder.build()).build();
                }
            }
            return request;
        }
    

    关于重构Request就是调用request.newBuilder()方法,该方法会把当前Request对象所以属性住一个copy,构建出新的Builder对象

    重写请求头 (拿的官方示例来做讲解)

    /** This interceptor compresses the HTTP request body. Many webservers can't handle this! */
    final class GzipRequestInterceptor implements Interceptor {
      @Override public Response intercept(Interceptor.Chain chain) throws IOException {
        Request originalRequest = chain.request();
        //如果请求头不为空,直接proceed
        if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
          return chain.proceed(originalRequest);
        }
        //否则,重构request
        Request compressedRequest = originalRequest.newBuilder()
            .header("Content-Encoding", "gzip")
            .method(originalRequest.method(), gzip(originalRequest.body()))
            .build();
        return chain.proceed(compressedRequest);
      }
    
      private RequestBody gzip(final RequestBody body) {
        return new RequestBody() {
          @Override public MediaType contentType() {
            return body.contentType();
          }
    
          @Override public long contentLength() {
            return -1; // We don't know the compressed length in advance!
          }
    
          @Override public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
          }
        };
      }
    }
    
    

    上面示例是对原始的request内容进行处理,貌似是对请求体进行gzip处理,这个一般是在响应头中的声明,请求头一般声明"Accept-Encoding"。

    对Response进行解析

     @Override
        public Response handlerResponse(DFBRestInterceptor.CustomResponse customResponse) {
            // 钥匙链对象chain 
            Interceptor.Chain chain = customResponse.chain;
            //真正的Response对象
            Response response = customResponse.response;
            //该请求的request对象
            Request request = chain.request();
            //获取Response结果
            String string = readResponseStr(response);
            JSONObject jsonObject;
            try {
                jsonObject = new JSONObject(string);
                //这个code就是服务器返回的错误码,假设300是时间戳异常
                int code = jsonObject.optInt("code");
                if (code == 300) {
                    //构造时间戳Request
                    Request time = new Request.Builder().url("http://192.168.1.125:8080/getServerTime").build();
                    //请求时间戳接口
                    Response timeResponse = chain.proceed(time);
                     //解析时间戳结果
                    String timeResStr = readResponseStr(timeResponse);
                    JSONObject timeObject = new JSONObject(timeResStr);
                    long date = timeObject.optLong("date");
                    TimeToken.TIME_TOKEN = date;
                    时间戳赋值,
                    if (date > 0) {
                        //重构Request请求
                        request = handlerRequest(CustomRequest.create(request));
                        //拿新的结果进行返回
                        response = chain.proceed(request);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return response;
        }
    
        /**
         * 读取Response返回String内容
         * @param response
         * @return
         */
        private String readResponseStr(Response response) {
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            try {
                source.request(Long.MAX_VALUE);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            MediaType contentType = body.contentType();
            Charset charset = Charset.forName("UTF-8");
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String s = null;
            Buffer buffer = source.buffer();
            if (isPlaintext(buffer)) {
                s = buffer.clone().readString(charset);
            }
            return s;
        }
    
        static boolean isPlaintext(Buffer buffer) {
            try {
                Buffer prefix = new Buffer();
                long byteCount = buffer.size() < 64 ? buffer.size() : 64;
                buffer.copyTo(prefix, 0, byteCount);
                for (int i = 0; i < 16; i++) {
                    if (prefix.exhausted()) {
                        break;
                    }
                    int codePoint = prefix.readUtf8CodePoint();
                    if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                        return false;
                    }
                }
                return true;
            } catch (EOFException e) {
                return false; // Truncated UTF-8 sequence.
            }
        }
        /**
         * 自定义Response对象,装载Chain和Response
         */
         public static class CustomResponse {
            public Response response;
            public Chain chain;
    
            public CustomResponse(Response response, Chain chain) {
                this.response = response;
                this.chain = chain;
            }
        }
    
    

    解析Response过程是对Reponse对象的操作,这里用的是Okio中的Source进行读取,参考的okhttp-logging-interceptor代码中的写法,在获取Reponse对象是,切不可直接操作response.body().bytes()或者 response.body().string(),数据只能读取一次,等着真正调用的时候, response.body().string()返回为null,这个问题描述在这里
    解决时间戳的问题,其实就是解析出结果中的错误码==300时(300是和服务器约定),构造出请求时间戳的Request,拿当前的Chain执行它就可以了,返回正确的时间戳之后,就可以拿正确的参数重构Request,然后Chain执行就Ok了。

    结束语:这些都是我自己使用的体会,没用Interceptor之前,我是把公共参数和加密放在网络请求之前处理,时间戳的处理,目前是用RxJava的map操作来处理,但是我觉得用Interceptor实现是最简洁的,准备下一步把它挪到Interceptor里,目前已知的缺点就是和OkHttp依赖太深,如果你的项目中已经集成OkHttp,机智的你可以动手试一试。

    相关文章

      网友评论

        本文标题:OkHttp3中Interceptor的使用心得

        本文链接:https://www.haomeiwen.com/subject/aczmpttx.html