【发布时间】:2016-05-23 12:01:34
【问题描述】:
欢迎大家,我目前正在开发一个网络服务,我在让这个方法与 ñ、ç、á、è、... 等字符一起工作时遇到了很多麻烦。这似乎与我的输入流,它似乎没有正确编码,这是代码:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url += urlParameters.toString();
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("charset", "utf-8");
con.setDoOutput(true);
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
//when i check 'con' all seems to be fine
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}
示例:
在“con”中 http:\direction.dom\data\W-S\something?param={example:"castaña"}
InputStream 返回:http:\direction.dom\data\W-S\something?param={example:"casta�a"}
提前致谢。
【问题讨论】:
-
“InputStream 返回”到底是什么意思?
responseString中的字符是否损坏?如果是这样,您如何确定字符串已损坏(而不是您用来查看字符串的任何内容,例如日志文件输出)? -
或者是 request URL 中的特殊字符?这些可能需要编码。
-
那么webservice使用什么编码来写入数据流呢?如果您不知道,请尝试“Cp1252”。这是 windows-1252 通常在西方国家的 Windows 中用作默认值。否则,您可以尝试将输入流中的原始字节写入文件并尝试使用文本编辑器打开它,希望编辑器能够猜出编码。
-
感谢您的提问,我说的是
in.readLine()。当我进行调试时,我检查了con中的数据和方法的参数,一切似乎都很好,但是当我执行inputLine = in.readLine()时,它会将损坏的字符放在inputLine中。 @vanje 如果我不这样做new InputStreamReader(con.getInputStream(), "UTF-8")我会在cp1252中获取数据,所以我猜cp1252是默认编码。 -
创建 InputStreamReader 时,将“UTF-8”替换为
new MimeType(con.getContentType()).getParameter("charset")。这样,您将始终使用正确的字符集,而不是盲目地假设 UTF-8。
标签: java web-services utf-8 http-post inputstream