OkHttp拦截器之获取Response.body的内容

本文介绍如何通过自定义OkHttp拦截器获取响应体内容,解决因读取响应体而导致后续操作失败的问题,并提供了一个完整的错误处理拦截器示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

OkHttp拦截器之获取Response.body的内容

项目中,由于使用了cookie,约定的有效期是20分钟,所以有可以会遇到cookie失效,无权操作,需要再次登录的情况。
在每个地方都进行无权操作error的处理显得不现实,于是就想到了使用拦截器。

但是当使用拦截器获取Response.body.string()后,后面的操作就直接返回Failed了,估计是因为流只能被使用一次的原因。

@Override
public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);
       
   		L.i("response.body.string:" + response.body().string());
       
		return response;	
}

后来,想到设置的 HttpLoggingInterceptor() 拦截器是如何获取到response的body的数据呢 ?

OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
						.build();  

于是乎是看了HttpLoggingInterceptor的源码

public final class HttpLoggingInterceptor implements Interceptor {
  private static final Charset UTF8 = Charset.forName("UTF-8");

  @Override public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();

	//如果Log Level 级别为NONOE,则不打印,直接返回
    if (level == Level.NONE) {
      return chain.proceed(request);
    }

	//是否打印body
    boolean logBody = level == Level.BODY;
    //是否打印header
	boolean logHeaders = logBody || level == Level.HEADERS;

	//获得请求body
    RequestBody requestBody = request.body();
	//请求body是否为空
    boolean hasRequestBody = requestBody != null;

	//获得Connection,内部有route、socket、handshake、protocol方法
    Connection connection = chain.connection();
	//如果Connection为null,返回HTTP_1_1,否则返回connection.protocol()
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
	//比如: --> POST http://121.40.227.8:8088/api http/1.1
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (!logHeaders && hasRequestBody) {
      requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

	//打印 Request
    if (logHeaders) {
      if (hasRequestBody) {
        // Request body headers are only present when installed as a network interceptor. Force
        // them to be included (when available) so there values are known.
        if (requestBody.contentType() != null) {
          logger.log("Content-Type: " + requestBody.contentType());
        }
        if (requestBody.contentLength() != -1) {
          logger.log("Content-Length: " + requestBody.contentLength());
        }
      }

      Headers headers = request.headers();
      for (int i = 0, count = headers.size(); i < count; i++) {
        String name = headers.name(i);
        // Skip headers from the request body as they are explicitly logged above.
        if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
          logger.log(name + ": " + headers.value(i));
        }
      }

      if (!logBody || !hasRequestBody) {
        logger.log("--> END " + request.method());
      } else if (bodyEncoded(request.headers())) {
        logger.log("--> END " + request.method() + " (encoded body omitted)");
      } else {
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);

		//编码设为UTF-8
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
          charset = contentType.charset(UTF8);
        }

        logger.log("");
        if (isPlaintext(buffer)) {
          logger.log(buffer.readString(charset));
          logger.log("--> END " + request.method()
              + " (" + requestBody.contentLength() + "-byte body)");
        } else {
          logger.log("--> END " + request.method() + " (binary "
              + requestBody.contentLength() + "-byte body omitted)");
        }
      }
    }

	//打印 Response
    long startNs = System.nanoTime();
    Response response;
    try {
      response = chain.proceed(request);
    } catch (Exception e) {
      logger.log("<-- HTTP FAILED: " + e);
      throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
	//比如 <-- 200 OK http://121.40.227.8:8088/api (36ms)
    logger.log("<-- " + response.code() + ' ' + response.message() + ' '
        + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", "
        + bodySize + " body" : "") + ')');

    if (logHeaders) {
      Headers headers = response.headers();
      for (int i = 0, count = headers.size(); i < count; i++) {
        logger.log(headers.name(i) + ": " + headers.value(i));
      }

      if (!logBody || !HttpEngine.hasBody(response)) {
        logger.log("<-- END HTTP");
      } else if (bodyEncoded(response.headers())) {
        logger.log("<-- END HTTP (encoded body omitted)");
      } else {
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
          try {
            charset = contentType.charset(UTF8);
          } catch (UnsupportedCharsetException e) {
            logger.log("");
            logger.log("Couldn't decode the response body; charset is likely malformed.");
            logger.log("<-- END HTTP");

            return response;
          }
        }

        if (!isPlaintext(buffer)) {
          logger.log("");
          logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
          return response;
        }

        if (contentLength != 0) {
          logger.log("");
			
		  //获取Response的body的字符串 并打印
          logger.log(buffer.clone().readString(charset));
        }

        logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
      }
    }

    return response;
  }

  /**
   * Returns true if the body in question probably contains human readable text. Uses a small sample
   * of code points to detect unicode control characters commonly used in binary file signatures.
   */
  static boolean isPlaintext(Buffer buffer) throws EOFException {
    try {
      Buffer prefix = new Buffer();
      long byteCount = buffer.size() < 64 ? buffer.size() : 64;
      buffer.copyTo(prefix, 0, byteCount);
      for (int i = 0; i < 16; i++) {
        if (prefix.exhausted()) {
          break;
        }
        int codePoint = prefix.readUtf8CodePoint();
        if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
          return false;
        }
      }
      return true;
    } catch (EOFException e) {
      return false; // Truncated UTF-8 sequence.
    }
  }

  private boolean bodyEncoded(Headers headers) {
    String contentEncoding = headers.get("Content-Encoding");
    return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
  }
}

然后,根据HttpLoggingInterceptor,就很容易得到responsebody的内容了

/**
 * @Description 异常处理 拦截器
 * Created by EthanCo on 2016/7/14.
 */
public class ErrorHandlerInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        
        //注意 >>>>>>>>> okhttp3.4.1这里变成了 !HttpHeader.hasBody(response)
        //if (!HttpEngine.hasBody(response)) { 
        if(!HttpHeaders.hasBody(response)){ //HttpHeader -> 改成了 HttpHeaders,看版本进行选择
		    //END HTTP
        } else if (bodyEncoded(response.headers())) {
            //HTTP (encoded body omitted)
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    //Couldn't decode the response body; charset is likely malformed.
                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                L.i("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                String result = buffer.clone().readString(charset);
                
				//获取到response的body的string字符串
				//do something .... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            }

            L.i("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
        return response;
    }
	   
    static boolean isPlaintext(Buffer buffer) throws EOFException {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
### OkHttp拦截器的使用场景和实现方式 OkHttp拦截器是一种强大的工具,用于在网络请求的生命周期中插入自定义逻辑。它可以通过两种类型的应用:应用拦截器(Application Interceptor)和网络拦截器(Network Interceptor),分别在不同的阶段对请求或响应进行处理[^3]。 #### 使用场景 1. **统一的日志记录** 拦截器可以用来记录所有请求和响应的详细信息,例如URL、请求头、请求、响应头和响应。这有助于调试和监控网络请求的行为。 ```java Interceptor loggingInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); System.out.println(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); System.out.println(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); return response; } }; ``` 2. **参数加密与解密** 在发送请求之前,可以对请求参数进行加密处理;在接收到响应后,可以对响应数据进行解密操作。这种场景特别适用于需要保护敏感数据的API调用[^4]。 ```java Interceptor encryptionInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request encryptedRequest = originalRequest.newBuilder() .header("Authorization", encryptToken(originalRequest.header("Authorization"))) .build(); return chain.proceed(encryptedRequest); } }; ``` 3. **URL重定向或修改** 如果某些请求不符合规则,拦截器可以动态地修改请求的URL或其他属性。 ```java Interceptor urlRewriteInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl url = originalRequest.url(); if (!url.host().equals("androidxx")) { return chain.proceed(originalRequest.newBuilder() .url("http://www.androidxx.cn") .build()); } return chain.proceed(originalRequest); } }; ``` 4. **统一设置编码格式** 拦截器可以确保所有请求和响应都使用统一的编码格式,例如UTF-8[^3]。 ```java Interceptor encodingInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); return response.newBuilder() .body(new GzipSource(response.body().source())) .build(); } }; ``` 5. **缓存控制** 网络拦截器可以在请求到达服务器之前或响应返回之后,添加或修改缓存相关的头信息[^3]。 ```java Interceptor cacheControlInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (isConnected()) { request = request.newBuilder() .header("Cache-Control", "public, max-age=" + 60) .build(); } else { request = request.newBuilder() .header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7) .build(); } return chain.proceed(request); } }; ``` #### 实现方法 OkHttp中的拦截器分为两类:应用拦截器和网络拦截器。它们的主要区别在于执行时机和作用范围。 1. **应用拦截器** 应用拦截器在请求被发送到网络层之前以及响应从网络层返回之后生效。它可以访问原始的请求和最终的响应。通过`OkHttpClient.interceptors()`方法注册应用拦截器[^2]。 ```java OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build(); ``` 2. **网络拦截器** 网络拦截器在网络层生效,只能访问经过重试或重定向后的请求和响应。它适用于需要直接操作HTTP协议的情况,例如添加缓存控制头或修改响应内容。通过`OkHttpClient.networkInterceptors()`方法注册网络拦截器[^2]。 ```java OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(cacheControlInterceptor) .build(); ``` --- ###
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

氦客

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值