Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end...
Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end...
·
异常分析:
根据关键异常信息:EOF一般指输入流达到末尾,无法继续从数据流中读取; 怀疑可能是由于双方(client<->server) 建立的连接,server端主动close了,为了验证以上猜想:github issue链接,根据@edallagnol 描述,当两次请求时间间隔超过server端配置的keep-alive timeout ,server端会主动关闭当前连接,Okhttp 连接池ConnectionPool 默认超时时间是5min,也就是说优先复用连接池中的连接,然而server已经主动close,导致输入流中断,进而抛出EOF 异常。其中keep-alive:两次请求之间的最大间隔时间 ,超过这个间隔 服务器会主动关闭这个连接, 主要是为了避免重新建立连接,已节约服务器资源。
解决方案:
- 根据上述分析,在创建OkHttpClient实例时,只需要将retryOnConnectionFailure设置为true ,在抛出EOF异常时,让其可以继续去执行realChain.proceed方法即可
- 在http请求头中添加request.addHeader(“Connection”, “close”),即不复用TCP长连接
- ConnectionPool 中连接默认超时时间是5min,可以减小超时时间,保证ConnectionPool中连接过期时间小于server端的keep_alive时间
更多推荐
所有评论(0)