關於取消OkHttp請求的問題

 

一.簡介

有時候網絡條件很差的狀況下,用戶會主動關閉頁面,這時候須要取消正在請求的http request, OkHttp提供了cancel方法,可是實際在使用過程當中發現,若是調用cancel()方法,會回調到CallBack裏面的 onFailure方法中,java

/**
   * Called when the request could not be executed due to cancellation, a connectivity problem or
   * timeout. Because networks can fail during an exchange, it is possible that the remote server
   * accepted the request before the failure.
   */
  void onFailure(Call call, IOException e);

能夠看到註釋,當取消一個請求,網絡鏈接錯誤,或者超時都會回調到這個方法中來,可是我想對取消請求作一下單獨處理,這個時候就須要區分不一樣的失敗類型了網絡

二.解決思路

測試發現不一樣的失敗類型返回的IOException e 不同,因此能夠經過e.toString 中的關鍵字來區分不一樣的錯誤類型ide

本身主動取消的錯誤的 java.net.SocketException: Socket closed
超時的錯誤是 java.net.SocketTimeoutException
網絡出錯的錯誤是java.net.ConnectException: Failed to connect to xxxxx

三.代碼

直貼了部分代碼測試

call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if(e.toString().contains("closed")) {
                 //若是是主動取消的狀況下
                }else{
                  //其餘狀況下
            }
     ....
相關文章
相關標籤/搜索