[英]Non-english letter in BufferedWriter
I've written a simple HTTP server in Java. 我已经用Java编写了一个简单的HTTP服务器。 I've a problem with returning data to the browser.
将数据返回到浏览器时出现问题。
This write a returned content: 这写了一个返回的内容:
this.writer = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream(), Charset.forName("UTF-8").newEncoder()));
...
writer.write(this.getResponseLine() + "\n");
writer.write("Content-Type: " + this.contentType + "; charset=utf-8\n");
writer.write("Content-Length: " + this.body.length() + "\n");
writer.write("\r\n");
writer.write(new String(this.body.getBytes(), "UTF-8"));
writer.flush();
writer.flush();
Method this.body.getBytes() returns "Witaj świecie", but in the brower is only "Witaj świeci" (missing the last letter). 方法this.body.getBytes()返回“ Witajświecie”,但是在浏览器中只有“ Witajświeci”(缺少最后一个字母)。
Where is the problem? 问题出在哪儿?
My guess is: this.body.length()
is the character count, not the byte count. 我的猜测是:
this.body.length()
是字符数,而不是字节数。 With one UTF8 character in there, the Content-Length
header will be too small by one byte, letting the browser stop reading from the socket before the HTTP message body actually ends. 在那里只有一个UTF8字符,
Content-Length
标头将太小一个字节,使浏览器在HTTP消息主体实际结束之前停止从套接字读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.