OkHttp3中Interceptor的使用心得

在看到這篇文章時(shí),希望你已經(jīng)閱讀過(guò)OkHttp對(duì)Interceptor的正式介紹,地址在這里,同時(shí),你還可以知道okhttp-logging-interceptor這個(gè)輔助庫(kù),當(dāng)然如果你沒(méi)有閱讀過(guò)也并無(wú)大礙,這篇文章重在描述使用場(chǎng)景和個(gè)人心得;

在去年網(wǎng)上討論最多的就是OkHttp和Volley的比較,我當(dāng)時(shí)決定把項(xiàng)目中的Volley換成OkHttp2,是因?yàn)樵谌蹙W(wǎng)環(huán)境下測(cè)試,OkHttp比較堅(jiān)強(qiáng),所以就用它了,并不是對(duì)Square的情懷;在一年多的使用中,不論是從2.x版本升到3.x,OkHttp絕對(duì)是最好用的庫(kù),特別是加之Retrofit,如虎添翼;

這篇文章是講Interceptor的使用心得,這就根據(jù)我所用,總結(jié)出這么幾點(diǎn):

  • Log輸出
  • 增加公共請(qǐng)求參數(shù)
  • 修改請(qǐng)求頭
  • 加密請(qǐng)求參數(shù)
  • 服務(wù)器端錯(cuò)誤碼處理(時(shí)間戳異常為例)

這幾點(diǎn)絕不是全面,但至少是目前很多開發(fā)者或多或少都會(huì)遇到的問(wèn)題,Log輸出是必須有的,公共參數(shù)這是必須有的,請(qǐng)求頭加密和參數(shù)加密,這個(gè)不一定都有;重點(diǎn)是服務(wù)端錯(cuò)誤碼處理,這個(gè)放在哪里處理,見仁見智,但是有些比較惡心的錯(cuò)誤,比如時(shí)間戳異常(請(qǐng)求任何一個(gè)服務(wù)器接口時(shí)必須攜帶時(shí)間戳參數(shù),服務(wù)器專門有提供時(shí)間戳的接口,這個(gè)時(shí)間戳要和服務(wù)器時(shí)間戳同步,容錯(cuò)在5秒,否則就返回時(shí)間戳錯(cuò)誤),比如客戶端修改系統(tǒng)時(shí)間時(shí)這一刻又?jǐn)嗑W(wǎng)了,監(jiān)聽時(shí)間變化也沒(méi)用,又不可能定時(shí)去獲取,所以何時(shí)需要同步,去請(qǐng)求這個(gè)接口成了問(wèn)題,我處理的方案是在Interceptor中過(guò)濾結(jié)果,當(dāng)某個(gè)接口返回時(shí)間戳異常時(shí),不把結(jié)果往上返,再執(zhí)行一次時(shí)間戳接口,如果獲取成功,傳入?yún)?shù)并重構(gòu)之前的請(qǐng)求,如果獲取失敗,把之前時(shí)間戳異常的接果返回。

說(shuō)了這幾條,其實(shí)具體實(shí)現(xiàn)要回歸到Interceptor這個(gè)類
我們要實(shí)現(xiàn):

  • 解析出來(lái)請(qǐng)求參數(shù)
  • 對(duì)請(qǐng)求進(jìn)行重構(gòu)
  • 解析出Response結(jié)果
  • 重構(gòu)Response

首先,Log輸出可以直接使用官方的https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
這只有一個(gè)類,我這篇文章解析Response的核心代碼其實(shí)是參考了這個(gè)庫(kù);

我們自己來(lái)做,第一步,就要實(shí)現(xiàn)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;}

如何解析出請(qǐng)求參數(shù)

        /**
         * 解析請(qǐng)求參數(shù)
         * @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方式的請(qǐng)求參數(shù)
         * @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;
        }

        /**
         * 獲取表單的請(qǐng)求參數(shù)
         * @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;
        }
}

解析參數(shù)就是判斷請(qǐng)求類型,get類型是從url解析參數(shù),其他類型是從FormBody取,可以上傳文件的表單請(qǐng)求暫時(shí)沒(méi)有考慮進(jìn)來(lái);

重構(gòu)Request增加公共參數(shù)

  @Override
    public Request handlerRequest(Request request) {
        Map<String, String> params = parseParams(Request);
        if (params == null) {
            params = new HashMap<>();
        }
        //這里為公共的參數(shù)
        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;
    }

關(guān)于重構(gòu)Request就是調(diào)用request.newBuilder()方法,該方法會(huì)把當(dāng)前Request對(duì)象所以屬性住一個(gè)copy,構(gòu)建出新的Builder對(duì)象

重寫請(qǐng)求頭 (拿的官方示例來(lái)做講解)

/** 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();
    //如果請(qǐng)求頭不為空,直接proceed
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
      return chain.proceed(originalRequest);
    }
    //否則,重構(gòu)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();
      }
    };
  }
}

上面示例是對(duì)原始的request內(nèi)容進(jìn)行處理,貌似是對(duì)請(qǐng)求體進(jìn)行g(shù)zip處理,這個(gè)一般是在響應(yīng)頭中的聲明,請(qǐng)求頭一般聲明"Accept-Encoding"。

對(duì)Response進(jìn)行解析

 @Override
    public Response handlerResponse(DFBRestInterceptor.CustomResponse customResponse) {
        // 鑰匙鏈對(duì)象chain 
        Interceptor.Chain chain = customResponse.chain;
        //真正的Response對(duì)象
        Response response = customResponse.response;
        //該請(qǐng)求的request對(duì)象
        Request request = chain.request();
        //獲取Response結(jié)果
        String string = readResponseStr(response);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(string);
            //這個(gè)code就是服務(wù)器返回的錯(cuò)誤碼,假設(shè)300是時(shí)間戳異常
            int code = jsonObject.optInt("code");
            if (code == 300) {
                //構(gòu)造時(shí)間戳Request
                Request time = new Request.Builder().url("http://192.168.1.125:8080/getServerTime").build();
                //請(qǐng)求時(shí)間戳接口
                Response timeResponse = chain.proceed(time);
                 //解析時(shí)間戳結(jié)果
                String timeResStr = readResponseStr(timeResponse);
                JSONObject timeObject = new JSONObject(timeResStr);
                long date = timeObject.optLong("date");
                TimeToken.TIME_TOKEN = date;
                時(shí)間戳賦值,
                if (date > 0) {
                    //重構(gòu)Request請(qǐng)求
                    request = handlerRequest(CustomRequest.create(request));
                    //拿新的結(jié)果進(jìn)行返回
                    response = chain.proceed(request);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 讀取Response返回String內(nèi)容
     * @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對(duì)象,裝載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過(guò)程是對(duì)Reponse對(duì)象的操作,這里用的是Okio中的Source進(jìn)行讀取,參考的okhttp-logging-interceptor代碼中的寫法,在獲取Reponse對(duì)象是,切不可直接操作response.body().bytes()或者 response.body().string(),數(shù)據(jù)只能讀取一次,等著真正調(diào)用的時(shí)候, response.body().string()返回為null,這個(gè)問(wèn)題描述在這里
解決時(shí)間戳的問(wèn)題,其實(shí)就是解析出結(jié)果中的錯(cuò)誤碼==300時(shí)(300是和服務(wù)器約定),構(gòu)造出請(qǐng)求時(shí)間戳的Request,拿當(dāng)前的Chain執(zhí)行它就可以了,返回正確的時(shí)間戳之后,就可以拿正確的參數(shù)重構(gòu)Request,然后Chain執(zhí)行就Ok了。

結(jié)束語(yǔ):這些都是我自己使用的體會(huì),沒(méi)用Interceptor之前,我是把公共參數(shù)和加密放在網(wǎng)絡(luò)請(qǐng)求之前處理,時(shí)間戳的處理,目前是用RxJava的map操作來(lái)處理,但是我覺(jué)得用Interceptor實(shí)現(xiàn)是最簡(jiǎn)潔的,準(zhǔn)備下一步把它挪到Interceptor里,目前已知的缺點(diǎn)就是和OkHttp依賴太深,如果你的項(xiàng)目中已經(jīng)集成OkHttp,機(jī)智的你可以動(dòng)手試一試。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,525評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,828評(píng)論 25 709
  • 在看到這篇文章時(shí),希望你已經(jīng)閱讀過(guò)OkHttp對(duì)Interceptor的正式介紹,地址在這里,同時(shí),你還可以知道o...
    poweru閱讀 882評(píng)論 1 1
  • 1.OkHttp源碼解析(一):OKHttp初階2 OkHttp源碼解析(二):OkHttp連接的"前戲"——HT...
    隔壁老李頭閱讀 12,190評(píng)論 31 62
  • 偶然無(wú)意間的邂逅 讓我重新把未來(lái)勾勒 一個(gè)勁的把文章瘋投 開始時(shí)的熱情過(guò)了頭 又重新用現(xiàn)實(shí)把自己看透 考慮到現(xiàn)在及...
    BULABULA小八閱讀 473評(píng)論 2 2

友情鏈接更多精彩內(nèi)容