GSON未发送UTF-8 [英] GSON not sending in UTF-8
问题描述
以下方法发送JSON答复.但是,在接收端,我一直收到无效字符,并且UTF-8不会解码数据.我在做什么错了?
The following method sends a JSON reply. However on the receiving end I keep getting invalid characters, and UTF-8 isn't decoding the data. What am I doing wrong?
响应客户端=数据输出流
//Get the client request
clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream())); //connectedclient = socket
//Start response object
responseToClient = new DataOutputStream(connectedClient.getOutputStream());
/**
* Sends a JSON response for an object
* @param objectToEncode
* @throws Exception
*/
private void sendJSONResponse(Object objectToEncode) throws Exception{
//Encode object into JSON
String jsonString = new Gson().toJson(objectToEncode);
// HTTP Header... Status code, last modified
responseToClient.writeBytes(HTTP_OK_STATUS_CODE);
responseToClient.writeBytes(CONTENT_TYPE_JSON);
responseToClient.writeBytes("Last-modified: "+ HelperMethods.now() +" \r\n");
responseToClient.writeBytes("\r\n");
// The HTTP content starts here
responseToClient.writeBytes(jsonString);
}
推荐答案
我不知道您为什么要编写自己的HTTP协议代码.就像编写自己的XML解析器一样:无论您多么优秀的程序员,都一定会出错.
I have no idea why you would write your own HTTP protocol code. It's a lot like writing your own XML parser: No matter how good a programmer you are, you are bound to get it wrong.
无论如何,如 DataOutputStream 文档所述,执行
Anyway, as the DataOutputStream documentation states, doing writeBytes
on a String will just discard its high eight bits. So what you get is... something, but not UTF8. What you should do is:
String jsonString = new Gson().toJson(objectToEncode);
byte[] utf8JsonString = jsonString.getBytes("UTF8");
responseToClient.write(utf8JsonString, 0, utf8JsonString.Length);
这篇关于GSON未发送UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!