从 Netty 中的 FullHttpResponse byteBuf 获取字符串内容

getting string content from FullHttpResponse byteBuf in Netty

我尝试了各种口味,但都给出了乱码结果。 但是浏览器上的响应看起来不错。 (清理 json 字符串)

    FullHttpResponse response = (FullHttpResponse) msg;
    byte[] bytes = new byte[response.content().readableBytes()];
    response.content().readBytes(bytes);
    String result = new String(bytes);

我按照建议尝试的另一个

response.content().toString(CharsetUtil.UTF_8);

两者都是这样的胡言乱语

P.S: 我在管道中使用了 HttpObjectAggregator 和 HttpServerCodec

您很可能正在查看压缩数据,因为您正在处理 FullHttpResponse 的实例,并且如今大多数服务器都使用压缩,因此您的数据很可能已被压缩。

要了解压缩背后的压缩算法,您应该查看response.headers().get(HttpHeaders.Names.CONTENT_ENCODING)

这可以return不同值的组合(在多个记录的情况下由,分隔):

  • gzip:数据使用GZip压缩
  • `deflate: 数据使用deflate压缩
  • identity: 没有发生压缩
  • br:数据使用brotli压缩

使用 FullHttpResponse 的一个优点是您不必担心正在使用的传输编码,因为它会为您处理。