简体   繁体   English

Netty中每个字符的响应有2个字节

[英]Response has 2 bytes per character in Netty

In Netty, I create a response by feeding a String in body : 在Netty中,我通过在body输入String来创建响应:

        DefaultFullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, httpResponse.getHttpResponseStatus());
        if (body != null) {
            ByteBuf buf = Unpooled.copiedBuffer(body, CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            res.headers().set(HttpHeaderNames.CONTENT_LENGTH, res.content().readableBytes());
        }

When I look at the response, I see content-length being twice the length of the characters in the String. 查看响应时,我看到content-length是String中字符长度的两倍。 I understand the Java String contains 2 bytes per character, but I can't figure out how to prevent this in Netty when returning the request. 我了解Java String每个字符包含2个字节,但是我不知道如何在返回请求时在Netty中防止这种情况。

When I look at Cloudflare responses, these contain one byte per character. 当我查看Cloudflare响应时,每个字符包含一个字节。 So there must be a way to change this. 因此,必须有一种方法来改变这一点。 Ideas? 有想法吗?

As @Chris O'Toole shows in How to convert a netty ByteBuf to a String and vice versa we must 正如@Chris O'Toole在如何将netty ByteBuf转换为String,反之亦然中所示,我们必须

  • first convert the String to Byte Array using the desired charset (UTF-8 works fine) String.getBytes(Charset) , 首先使用所需的字符集将字符串转换为字节数组(UTF-8可以正常工作) String.getBytes(Charset)
  • then Unpooled.wrappedBuffer(byte[]) using the Byte Array instead the String. 然后使用字节数组而不是字符串Unpooled.wrappedBuffer(byte[])

One byte per character for most characters, as @rossum stated. 如@rossum所述,对于大多数字符,每个字符一个字节。

Use US_ASCII charset instead of UTF-8. 使用US_ASCII字符集而不是UTF-8。 Haven't tested, try. 尚未测试,请尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM