美文网首页拦截器
使用okHttp3拦截器统一加密解密(1)

使用okHttp3拦截器统一加密解密(1)

作者: galaxy_zheng | 来源:发表于2019-10-08 09:06 被阅读0次

    layout: post

    title: '如何使用okHttp拦截器统一解密(1)'

    subtitle: '转载请注明出处'

    date: 2019-08-30

    categories: Android okHttp3

    cover: 'http://bpic.588ku.com/back_pic/05/56/83/235b206f30d6d48.jpg'

    tags: Android okHttp3


    自定义拦截器可以先客户端一步拿到每一次 Http 请求的结果做一些额外处理

    example:解密、token过期后重新请求等

    public class ResponseInterceptor implements Interceptor {
        private static final String TAG = "ResponseInterceptor";
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            //返回request
            Request request = chain.request();
            //返回response
            Response response = chain.proceed(request);
            //isSuccessful () ; 如果代码在[200..300]中,则返回true,这意味着请求已成功接收、理解和接受。
            if (response.isSuccessful()) {
                //返回ResponseBody
                ResponseBody responseBody = response.body();
                if (responseBody != null) {
                    try {
                        //获取bodyString
                        BufferedSource source = responseBody.source();
                        source.request(Long.MAX_VALUE);
                        Buffer buffer = source.buffer();
                        Charset charset = Charset.forName("UTF-8");
                        MediaType contentType = responseBody.contentType();
                        if (contentType != null) {
                            charset = contentType.charset(charset);
                        }
                        String bodyString = buffer.clone().readString(charset);
                        //我这里是base64解码  具体情况自己定义
                        //base64解码
                        String responseData = new String(EncodeUtils.base64Decode(bodyString));
                        //生成新的ResponseBody
                        ResponseBody newResponseBody = ResponseBody.create(contentType, responseData.trim());
                        //response
                        response = response.newBuilder().body(newResponseBody).build();
                         Log.i(TAG, "解密后数据: " + responseData);
    
                    } catch (IOException e) {
                        //如果发生异常直接返回
                        e.printStackTrace();
                        return response;
                    }
                } else {
                    Log.i(TAG, "onHttpResultResponse: 响应体为空");
                }
            }
            return response;
        }
    
    }
    

    相关文章

      网友评论

        本文标题:使用okHttp3拦截器统一加密解密(1)

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