Java HttpUrlConnection POST 请求特殊字符奇怪的行为

Ve9*_*Ve9 2 java post http utf-8 httpurlconnection

我正在尝试使用 HttpURLConnection 实现 POST 请求。这是我的代码:

\n\n
private static void call(String body) throws IOException{\n    HttpURLConnection con = null;\n\n    con = (HttpURLConnection)new URL("http://127.0.0.1:8080").openConnection();\n\n    con.setRequestProperty("Accept-Charset", "UTF-8");\n    con.setRequestMethod("POST");\n    con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); \n    con.setRequestProperty("Accept", "application/json; charset=utf-8");\n\n    con.setDoOutput(true);\n    DataOutputStream wr = new DataOutputStream(con.getOutputStream());\n    wr.writeBytes(body);\n    wr.flush();\n    wr.close();\n    ...\n }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我将其发布到本地主机只是为了用 WireShark 嗅探它。\n问题是,当我的正文是包含诸如 \' \xc3\xb2 \' \' \xc3\xa0 \' \' \xc3\xa8 \'之类的字符的字符串时\' \xc3\xa7 \' ...我看到的请求的字符串正确,这些字符被点替换。

\n\n

示例:\nif 正文是“ h\xc3\xa8llo! ” ---> 请求正文是“ h.llo!

\n\n

只是为了测试,我在 java main 中执行上述方法,并以这种方式传递参数:

\n\n
String pString = "{\\"titl\xc3\xa8\\":\\"H\xc3\xa8llo W\xc3\xb2rld!\\"}";\nString params = new String(pString.getBytes("UTF-8"),"UTF-8");\n....\ncall(body);\n
Run Code Online (Sandbox Code Playgroud)\n\n

这就是我在 WireShark 中得到的:

\n\n
POST / HTTP/1.1\nAccept-Charset: UTF-8\nContent-Type: application/json; charset=utf-8\nAccept: application/json; charset=utf-8\nUser-Agent: Java/1.6.0_43\nHost: 127.0.0.1:8080\nConnection: keep-alive\nContent-Length: 24\n\n{"titl.":"H.llo W.rld!"}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如有任何帮助,我们将不胜感激。\n谢谢

\n

Chr*_*phT 6

Java 中的内部字符串表示形式始终为 UTF-16。因此,在第二个示例中params = new String(pString.getBytes("UTF-8"),"UTF-8");,将 pString 转换为包含 UTF-8 内容的字节数组,然后转换回存储在 params 中的 UTF-16。当字符串进入或离开虚拟机时,每个编码都必须完成。这意味着在您的情况下,您必须在将正文写入流时设置编码。

wr.write(body.getBytes("UTF-8"));
Run Code Online (Sandbox Code Playgroud)