OK HTTP异常记录

3 篇文章 1 订阅

1、Okhttp java.io.EOFException: \n not found: size=0 content= unexpected end

EOF一般指输入流达到末尾,无法继续从数据流中读取; 怀疑可能是由于双方(client<->server) 建立的连接,某一方主动close了。

根据@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();
   }
 

源码分析
在进行常规的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 处理拦截器这块,用到了责任链模式

解决方案
根据上述分析,在创建OkHttpClient实例时,只需要将retryOnConnectionFailure设置为true ,在抛出EOF异常时,让其可以继续去执行realChain.proceed方法即可。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在RESTful API中,错误和异常情况应该以适当的方式进行处理和返回给客户端。以下是一些常见的处理错误和异常的方法: 1. 使用适当的HTTP状态码:根据错误或异常的类型,选择合适的HTTP状态码来表示请求的结果。常见的状态码包括: - 200 OK:请求成功 - 201 Created:成功创建资源 - 400 Bad Request:请求无效或参数错误 - 401 Unauthorized:未经授权,需要进行身份验证 - 404 Not Found:请求的资源不存在 - 500 Internal Server Error:服务器内部错误 2. 提供有意义的错误信息:在响应中,包含有关错误或异常的信息,以帮助客户端进行故障排除。可以使用JSON格式或其他适合的数据格式来传递错误信息,例如: ``` { "error": { "code": 400, "message": "Invalid request parameter" } } ``` 3. 异常处理中间件:在API的代码中,使用异常处理中间件来捕获和处理任何发生的异常。这样可以防止未处理的异常导致服务器崩溃,并提供自定义的错误响应。 4. 请求验证和输入验证:在处理请求之前,对请求进行验证以确保其有效性和完整性。例如,验证必需的参数是否存在、验证输入数据是否符合预期的格式等。 5. 记录错误日志:在服务器端记录错误日志,以便进行故障排除和问题追踪。可以记录错误的时间、请求信息、错误类型和堆栈跟踪等。 6. 版本控制:如果API有多个版本,可以使用版本控制来处理错误和异常情况。这样可以确保在引入更改时不会中断现有客户端的功能,并提供逐步迁移的机会。 通过这些方法,可以更好地处理RESTful API中的错误和异常情况,并提供清晰和有用的错误信息给客户端,以便于故障排除和问题解决。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值