简体   繁体   中英

Non-english letter in BufferedWriter

I've written a simple HTTP server in Java. 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).

Where is the problem?

My guess is: this.body.length() is the character count, not the byte count. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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