一.簡介
有時候網絡條件不好的情況下,用戶會主動關閉頁面,這時候需要取消正在請求的http request, OkHttp提供了cancel方法,但是實際在使用過程中發現,如果調用cancel()方法,會回調到CallBack里面的 onFailure方法中,
/**
* 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 中的關鍵字來區分不同的錯誤類型
自己主動取消的錯誤的 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{
//其他情況下
}
....