java - inputStream 编码问题(特殊字符 : ñ, á,...)

标签 java web-services utf-8 http-post inputstream

欢迎大家,我目前正在开发一个网络服务,要让这个方法处理像 ñ、ç、á、è、... 这样的字符,我遇到了很多麻烦,它似乎与我的输入流有关,它似乎没有正确编码,这是代码:

    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-1ISO-8859-15windows-1252

您可以通过为 Web 表单设置正确的 HTTP header 来插入用户使用 UTF-8:response.setContentType("text/xml; charset=utf-8):

关于java - inputStream 编码问题(特殊字符 : ñ, á,...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37390484/

相关文章:

通过 http (apache httpd) 的 Perl CGI 脚本打印(utf-8 编码 - 日文 html)被截断

java - Spring Batch 管理员挂起在部署时注册步骤执行

java - 如何手动加密 SOAP 消息?

java - 开发了解用户时区的网络服务

java - maven-jaxws-tools-plugin 错误 : ClassNotFoundException

java - 如何将 Modified-UTF8 中的 byte[] 转换为字符串?

java - 如何在日语 utf-8 汉字上使用 java 子字符串

java随机化数组中的索引

java - Maven Tomcat插件-无法调用Tomcat管理器

java - 避免java中的特定异常