retrofit+rxjava2使用中遇到的一些问题

retrofit+rxjava2使用中遇到的一些问题

1、网络code为204或者205不回调问题

原因:retrofit中OkHttpCall里此处拦截了导致,需要自己针对此种情况处理

OkHttpCall:210行

if (code == 204 || code == 205) {
  rawBody.close();
  return Response.success(null, rawResponse);
}

ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
  T body = serviceMethod.toResponse(catchingBody);
  return Response.success(body, rawResponse);
} catch (RuntimeException e) {
  // If the underlying source threw an exception, propagate that rather than indicating it was
  // a runtime exception.
  catchingBody.throwIfCaught();
  throw e;
}

解决:

需要在自定义的公共常规拦截器的intercept处理:

具体如下:

如HttpBaseInterceptor 里intercept里

        Response response = chain.proceed(oldRequest);
        Logger.e("HttpBaseInterceptor", "chain.proceed 耗时:" + (System.currentTimeMillis() - currentTime));
        int responseCode = 0;
        if (response != null) {
            responseCode = response.code();
        }
        // Throw specific Exception on HTTP 204 or 205 response code,让项目封装的rxjava2的对应自定义scriberCallBack的onError去统一处理
        //此处不拦截处理,204或205 就会无法回调
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            throw new ResultException(String.valueOf(responseCode), ConstantNet.NET_ERROR);
        }
        return response;

抛出异常可以参考RealInterceptorChain.java:147行的;抛出异常后rxjava2会捕获回调到onError里,在自定义的Subscriber的onError(Throwable e)就可以监听 此种情况,并专门处理回调到Presenter层或者UI层

 

也可以参考:http://www.chinaoc.com.cn/p/1221632.html

 

2、上传文件出现进度条200%或者300%的问题

原因:多处调用了requestBody.writeTo,在uploadFileRequestBody中会执行多次就会导致

解决:uploadFileRequestBody里重写的writeTo根据BufferedSink的类型进行区分解决;

日志拦截器中的 BufferedSink 是 Buffer 类型,而实际进行网络请求的 BufferedSink 是 FixedLengthSink。所以修改 ProgressRequestBody 里的 writeTo(BufferedSink sink) 方 法,如果传入的 sink 为 Buffer 对象,则直接写入,不进行统计。

代码如下:

修改UploadFileRequestBody里的writeTo,增加的加粗区域

@Override
public void writeTo(BufferedSink sink) throws IOException {
    if (sink instanceof Buffer) {
        // Log Interceptor
        mRequestBody.writeTo(sink);
        return;
    }
    CountingSink countingSink = new CountingSink(sink);
    BufferedSink bufferedSink = Okio.buffer(countingSink);
    //写入
    mRequestBody.writeTo(bufferedSink);
    //刷新
    //必须调用flush,否则最后一部分数据可能不会被写入
    bufferedSink.flush();
}

 

也可参考:

https://blog.csdn.net/maosidiaoxian/article/details/78635550

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值