在发送我的 JSON 响应时,我以可见的形式显示内容类型。这是一个问题,因为当我在另一端解析 JSON 时,它包含标头并且无法解析回哈希图。
我应该如何编码这个响应,以便标题不会“显示”
这是生成响应的方法
/**
* Sends reply back to client
* @throws Exception
*/
private void sendResponse() throws Exception{
//Content type
String contentTypeLine = "Content-Type: text/json" + "\r\n";
//Create dummy JSON object
HashMap<String, String> mapResponse = new HashMap<String, String>();
mapResponse.put("Author", "James");
mapResponse.put("Author 2", "John");
//Convert to JSON
Gson gson = new Gson();
String json = gson.toJson(mapResponse);
//Set type
responseToClient.writeBytes(contentTypeLine);
//Set JSON
responseToClient.writeBytes(json);
}
这是示例响应
Content-Type: text/json
{"Author":"James","Author 2":"John"}
请求获取代码
/**
* Code to execute on thread
*/
public void run(){
try {
//Log new client
System.out.println("The client " + connectedClient.getInetAddress() +
":" + connectedClient.getPort() + " is connected");
//Get the client request
clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));
//Start response object
responseToClient = new DataOutputStream(connectedClient.getOutputStream());
//Process the request
processClientRequest();
//Close buffered writer
responseToClient.close();
} catch (Exception e) {
//Print error
e.printStackTrace();
}
}
谢谢!