[英]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,反之亦然中所示,我们必须
String.getBytes(Charset)
, String.getBytes(Charset)
, 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.