关于取消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{
                  //其余状况下
            }
     ....
相关文章
相关标签/搜索