java socket 发送失败,HTTP失败:java.net.SocketException:套接字已关闭;不会触发异常处理方法...

I have an RxJava chain request that should release some locks onError(), or onComplete(), so, basically, what my problem is: when I set read, connect and write timeouts to my OkHttpClient, I don't get the desired behavior. I'm using Retrofit2 and OkHttp3.6.0 Here's my simplified client:

OkHttpClient.Builder builder = new OkHttpClient.Builder()

.readTimeout(30, TimeUnit.SECONDS)

.connectTimeout(30, TimeUnit.SECONDS)

.writeTimeout(30, TimeUnit.SECONDS)

OkHttpClient okHttpClient = builder.build();

Here's a simplified version of the chain request I have:

public Observable doSomething(Observable base) {

isLocked = true;

return someApiCall()

.flatMap(apiResponse -> handleResponse(apiResponse, base)

.doOnError(throwable -> {

isLocked = false;

})

.doOnCompleted(() -> {

isLocked = false;

}));

}

handleResponse() makes another API call and returns an Observable> but, as I've said, it sometimes fails with a HTTP FAILED: java.net.SocketException: Socket closed and it never finishes the Observable, so, onError() or onComplete() are never called. I've tried onTerminate() also, but with no luck. When I remove the timeout settings from the OkHttlClient, the SocketException is actually thrown and caught which releases the isLocked variable. I've tried wrapping the handleResponse() return statement with a try {} catch (Exception e) {} block, but even that doesn't catch the SocketException when the custom timeouts are set. Any ideas?

解决方案

It turns out that the request was getting unsubscribed, which caused the appearance of the HTTP FAILED: java.net.SocketException: Socket closed error, so, the solution was just adding this code to the chain:

.doOnUnsubscribe(() -> {

isLocked = false;

})

I still don't understand why the custom timeout value was triggering the SocketException, but I suppose that the socket was waiting for the timeout to expire and close, or complete the request and close, but it got interrupted by the unsubscribe call and thus closed unexpectedly.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值