utf8中的HTTP HTTP服务器响应
我有一个http服务器接收POST请求并从mysql数据库提取数据。
这是服务器的相关部分:
utf8中的HTTP HTTP服务器响应
@Override
public void handle(HttpExchange he) throws IOException {
JSONArray jsonArr = null;
InputStreamReader isr = new InputStreamReader(he.getRequestBody(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
JSONObject postData=null;
try {
postData=Constants.parseQuery(query);
} catch (JSONException e) {
System.out.println("ERROR: SelectHandler,handle,parseQuery, on query: " + query);
}
// Object t=params.entrySet().
try {
query=Constants.getSelectQuery(postData);
jsonArr = MySQLQueryExecutor.getInstance().getItems(query);
} catch (JSONException e) {
System.out.println("ERROR: SelectHandler,handle,getItems, on query: " + query);
}
String encoding = "UTF-8";
String ret=jsonArr.toString();
he.getResponseHeaders().set("Content-Type", "application/json; charset=" + encoding);
he.sendResponseHeaders(200, ret.length());
System.out.println(ret);
OutputStream os = he.getResponseBody();
ret= URLDecoder.decode(ret, "UTF-8");
os.write(ret.toString().getBytes());
os.close();
}
我可以看到,服务器处理请求并发送响应,但在客户端上我得到一个错误。
错误是由于响应中的utf8字符(希伯来字符,当我忽略它们时,错误消失了)。
我该如何解决这个问题?这是服务器还是客户端问题?
长度也是错误的。有点进一步:
String encoding = "UTF-8";
String ret = jsonArr.toString();
he.getResponseHeaders().set("Content-Type", "application/json; charset=" + encoding);
//ret= URLDecoder.decode(ret, "UTF-8");
byte[] bytes = ret.getBytes(StandardCharsets.UTF_8);
he.sendResponseHeaders(200, bytes.length);
System.out.println(ret);
OutputStream os = he.getResponseBody();
os.write(bytes);
os.close();
这对我有效。谢谢! –
...但它仍然有一个破碎的内容类型。 –
mime类型应该只是'application/json'或一个回调'application/javascript'。该字符集仅用于'text/...'。默认为json _is_ UTF-8。是否有一个'addResponseHeaders'来添加两个头文件? –
a)您有一个破损的Content-Type标题字段。 application/json中没有字符集参数。见https://greenbytes.de/tech/webdav/rfc7159.html#rfc.section.11
b最后一句)您需要发送从String.getBytes获得的字节(“UTF-8”)和
C)这也是如何计算内容长度(编码为UTF经过这么-8个字节,而不是之前)。
os.write(ret.getBytes(encoding));不起作用。我也删除了损坏的标题。不过,同样的错误。 –
不确定你的意思,但你写了Content-Tye而不是Content-Type。 – Qix
Content-Type标头是正确的,你总是可以为JSON MIME类型添加一个字符集。根据RFC 4627,只有默认编码是UTF,所以在这里不需要。 –
'URLDecoder'完全不是你想要的。您需要编写字符串的UTF8字节。 – SLaks
os.write(ret.getBytes(encoding));没有帮助,如果那你的意思 –
你实际收到什么回应? – SLaks