記一次使用Okhttp遇到的坑!!!
阿新 • • 發佈:2019-01-07
在使用Okhttp的過程中頻繁的發起Http請求時偶爾會看到如下的錯誤
ERROR [IOException]-[120]
java.io.IOException: unexpected end of stream on [email protected]
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:201)at okhttp3.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:53)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
at okhttp3.RealCall.access$100(RealCall.java:33)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:120)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.io.EOFException: \n not found: size=0 content=…
at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:215)
at okhttp3.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
... 21 more
不知是Okhttp的一個bug還是什麼奇妙的原因。功夫不負有心人苦逼的找了一個下午,終於找到了一個解決方案,就是在http的頭部新增addHeader("Connection", "close"),
即增加關閉連線,不讓它保持連線。後來自己測試一番貌似再沒有出現過上面的問題了。
不加頭部時Connection的值為Keep-Alive
增加Connection=false後頭部如下:
關於Http頭 Connection=close的作用:
在http1.1中request和reponse header中都有可能出現一個connection頭欄位,此header的含義是當client和server通訊時對於長連結如何進行處理。在http1.1中,client和server都是預設對方支援長連結的, 如果client使用http1.1協議,但又不希望使用長連結,則需要在header中指明connection的值為close;如果server方也不想支援長連結,則在response中也需要明確說明connection的值為close.
不論request還是response的header中包含了值為close的connection,都表明當前正在使用的tcp連結在請求處理完畢後會被斷掉。以後client再進行新的請求時就必須建立新的tcp連結了。 HTTP Connection的 close設定允許客戶端或伺服器中任何一方關閉底層的連線雙方都會要求在處理請求後關閉它們的TCP連線。