以下方法发送 JSON 回复。但是在接收端,我不断收到无效字符,并且 UTF-8 没有解码数据。我究竟做错了什么?
响应客户端=数据输出流
//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);
}