关于使用okhttp3响应乱码问题

结论

  1. 去除application.yml中的压缩配置
  2. 配置响应拦截器,解压缩响应体
/**
 * 响应解压缩拦截器
 *
 * @author zhang.rx
 * @since 2024/4/11
 */
public class ResponseCompressionInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        // 响应头的Content-Encoding中包含gzip,说明响应需要解压
        if ("gzip".equalsIgnoreCase(originalResponse.header("Content-Encoding"))) {
            return originalResponse.newBuilder()
                    .body(gzip(originalResponse))
                    .build();
        }
        return originalResponse;
    }

    private ResponseBody gzip(Response response) throws IOException {
        BufferedSource source = Okio.buffer(new GzipSource(response.body().source()));
        return ResponseBody.create(response.body().contentType(), response.body().contentLength(), source);
    }
}

然后在创建OkHttpClient.Builder()的地方配置拦截器

OkHttpClient.Builder().addInterceptor(new ResponseCompressionInterceptor())

出现场景

服务1 通过 okhttp3 去请求 服务2 的接口,但是服务2由于在application.yml中配置了:

server:
  compression:
	enabled: true
    mime-types: application/json,text/plain

导致服务2在响应的时候会将json进行压缩,然后返回数据给服务1

当然,将enabled设置为false,不加拦截器也可以达到相同的效果。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值