記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

why發表於2018-07-30

問題猜想

由於此問題不是必現,故不太好定位排查,根據關鍵異常資訊:EOF一般指輸入流達到末尾,無法繼續從資料流中讀取; 懷疑可能是由於雙方(client<->server) 建立的連線,某一方主動close了,為了驗證以上猜想,筆者查閱了相關資料,以及做了一些簡單的程式碼實驗

如何解決

Github Issue or google or stackoverflow?

記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

截圖連結

根據@edallagnol 描述,當兩次請求時間間隔超過server端配置的keep-alive timeout ,server端會主動關閉當前連線,Okhttp 連線池ConnectionPool 預設超時時間是5min,也就是說優先複用連線池中的連線,然而server已經主動close,導致輸入流中斷,進而丟擲EOF 異常。其中keep-alive兩次請求之間的最大間隔時間 ,超過這個間隔 伺服器會主動關閉這個連線, 主要是為了避免重新建立連線,已節約伺服器資源

問題復現:

// Note: 需要保證server端配置的keep-alive timeout 為60s
OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .build();
try {
       for (int i = 0; i != 10; i++) {
           Response response = client.newCall(new Request.Builder()
                    .url("http://192.168.50.210:7080/common/version/demo")
                    .get()
                    .build()).execute();
               try {
                  System.out.println(response.body().string());
               } finally {
                    response.close();
               }
               Thread.sleep(61000);
            }
        } catch (Exception e) {
            e.printStackTrace();
   }

複製程式碼

記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

原始碼分析

在進行常規的breakpoint之後, 需要重點關注 RetryAndFollowUpInterceptor.java Http1Codec.java RealBufferedSource.java 這幾個類

RetryAndFollowUpInterceptor.java 

public class RetryAndFollowUpInterceptor implements Interceptor {
   
   //....
   
   @Override public Response intercept(Chain chain) throws IOException {
        //....
        while(true) {
          try {
            response = realChain.proceed(request, streamAllocation, null, null);
           releaseConnection = false;
      } catch (IOException) {
           // An attempt to communicate with a server failed. The request may have been sent.
        boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
        // 此處非常重要,若不允許恢復,直接將異常向上丟擲(呼叫方接收),反之 迴圈繼續執行realChain.proceed()方法
        if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
        releaseConnection = false;
        continue;  
      }
   
   }

    
    private boolean recover(IOException e, StreamAllocation streamAllocation,
      boolean requestSendStarted, Request userRequest) {
         
         // ....
         
         / The application layer has forbidden retries.
        // 若客戶端配置 retryOnConnectionFailure 為false 則表明不允許重試,直接將異常拋給呼叫方
        if (!client.retryOnConnectionFailure()) return false;
        
    }

    //....
}
複製程式碼

當執行realChain.proceed() ,將事件繼續分發給各個攔截器,最終執行到 Http1Codec#readResponseHeaders 方法

Http1Codec.java

public class Http1Codec implements HttpCodec {
    //...
    @Override public Response.Builder readResponseHeaders(boolean expectContinue) throws IOException {
       try{
          StatusLine statusLine = StatusLine.parse(readHeaderLine());
          //後續程式碼根據statusLine 構造Response
       } catch(EOFException e) {
           // 原來異常資訊就是從這裡丟擲來的,接下來需要重點關注下readHeaderLine方法
           // Provide more context if the server ends the stream before sending a response.
           IOException exception = new IOException("unexpected end of stream on " + streamAllocation);
           exception.initCause(e);
       }
    }
    private String readHeaderLine() throws IOException {
        // 繼續檢視RealBufferedSource#readUtf8LineStrict方法
        String line = source.readUtf8LineStrict(headerLimit);
        headerLimit -= line.length();
        return line;
    }    
   //...
}
複製程式碼

Http1Codec 用於Encode Http Request 以及 解析 Http Response的,上述程式碼用於獲取頭資訊相關引數

RealBufferedSource.java
final class RealBufferedSource implements BufferedSource {
   //...
   // 由於server端已經closed,故buffer == null 將EOF異常向上丟擲
   @Override public String readUtf8LineStrict(long limit) throws IOException {
    if (limit < 0) throw new IllegalArgumentException("limit < 0: " + limit);
    long scanLength = limit == Long.MAX_VALUE ? Long.MAX_VALUE : limit + 1;
    long newline = indexOf((byte) '\n', 0, scanLength);
    if (newline != -1) return buffer.readUtf8Line(newline);
    if (scanLength < Long.MAX_VALUE
        && request(scanLength) && buffer.getByte(scanLength - 1) == '\r'
        && request(scanLength + 1) && buffer.getByte(scanLength) == '\n') {
      return buffer.readUtf8Line(scanLength); // The line was 'limit' UTF-8 bytes followed by \r\n.
    }
    Buffer data = new Buffer();
    buffer.copyTo(data, 0, Math.min(32, buffer.size()));
    throw new EOFException("\\n not found: limit=" + Math.min(buffer.size(), limit)
        + " content=" + data.readByteString().hex() + '…');
  }
  //...
}
複製程式碼

用一張圖總結:

記錄某次解決`Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

可以看出 Okhttp 處理攔截器這塊,用到了責任鏈模式

解決方案

根據上述分析,在建立OkHttpClient例項時,只需要將retryOnConnectionFailure設定為true ,在丟擲EOF異常時,讓其可以繼續去執行realChain.proceed方法即可

相關文章