欢迎大家,我目前正在开发一个网络服务,要让这个方法处理像 ñ、ç、á、è、... 这样的字符,我遇到了很多麻烦,它似乎与我的输入流有关,它似乎没有正确编码,这是代码:
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"}
输入流返回:http:\direction.dom\data\W-S\something?param={example:"casta�a"}
提前致谢。
最佳答案
这是一个非常棘手的情况,因为您正在处理 HTTP 参数。这些可以是用户在浏览器中输入的任何编码。
根据您的示例,您的用户以 UTF-8
以外的其他方式发送数据。它可以是 ISO-8859-1
、ISO-8859-15
或 windows-1252
。
您可以通过为 Web 表单设置正确的 HTTP header 来插入用户使用 UTF-8:response.setContentType("text/xml; charset=utf-8)
:
关于java - inputStream 编码问题(特殊字符 : ñ, á,...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37390484/