IOException: unexpected end of stream on Connection的解决方法

测试小哥跟我说偶有网络连接错误的问题,看了一下日志,方法报了这个错误IOException: unexpected end of stream on Connection。我去网上找了找一般这个问题出现的原因有一下两种,不过我的是第二种原因:

1、首先在github上看到这个问题的解释:The error occurs when OkHttp try to reuse a connection that is in FIN_WAIT2 state in server, because the server keep_alive timeout is lesser than the client timeout.  于是发现了我这代码可能出问题的地方,我的okhttp设置的timeout是100,而服务器一般是60修改后暂时没发生过这个问题。

2、IOException: unexpected end of stream on Connection这个产生的原因是和okhttp和版本都有关系,需要在拦截器中增加一个addHeader("Connection","close")。写法如下:

if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {

urlConnect.setRequestProperty("Connection", "close");

}

或者重新写一个拦截器如:

class   NetInterceptor   implements   Interceptor {

@Override

public Responseintercept(Chain chain)throws IOException {

Request request = chain.request().newBuilder()

.addHeader("Connection","close").build();

returnchain.proceed(request);

}

}

OkHttpClient client =newOkHttpClient.Builder()

.addNetworkInterceptor(new NetInterceptor())

.build();

}

这个出现原因说白就是server和client中tcp链接的原因,增加addHeader("Connection","close")后当请求处理完后会断掉,之后在每次请求都会创建新的tcp链接。

我又在网上找到了一段关于这个的描述,在http1.1中request和reponse header中都有可能出现一个connection头字段,此header的含义是当client和server通信时对于长链接如何进行处理。

在http1.1中,client和server都是默认对方支持长链接的, 如果client使用http1.1协议,但又不希望使用长链接,则需要在header中指明connection的值为close;如果server方也不想支持长链接,则在response中也需要明确说明connection的值为close.


感谢一下博客:http://blog.csdn.net/mace_android/article/details/72121638 ,http://www.jianshu.com/p/dea2ffb1c3b1 ,http://blog.csdn.net/blackice1015/article/details/51018815

你可能感兴趣的:(IOException: unexpected end of stream on Connection的解决方法)