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

时间:2016-05-23 12:01:34

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

欢迎大家,我目前正在开发一个网络服务,我很难让这个方法与ñ,ç,á,è等字符一起工作......这似乎与我的输入流,它似乎没有正确编码,这是代码:

template <class A, class... As>
class Foo : public Foo<As...>
{
protected:
    using Foo<As...>::foo;
public:
    using Foo<As...>::bar;
    void bar(const A& a) { foo(a); }
};

template <class A>
class Foo<A>
{
protected:
    template <class T>
    void foo(const T& t) {  }
public:
    void bar(const A& a) { foo(a); }
};

实施例: 在里面“con”http:\ direction.dom \ data \ W-S \ something?param = {例如:“castaña”}
和InputStream返回:http:\ direction.dom \ data \ W-S \ something?param = {example:“casta a”}

提前致谢。

2 个答案:

答案 0 :(得分:0)

这是一个非常棘手的案例,因为您正在处理HTTP参数。这些可以是用户在浏览器中输入的任何编码。

根据您的示例,您的用户以UTF-8以外的其他内容发送数据。它可以是ISO-8859-1ISO-8859-15windows-1252

您可以通过将正确的HTTP标头设置为您的网络表单,将您的用户推向UTF-8:response.setContentType("text/xml; charset=utf-8)

答案 1 :(得分:0)

我的合作伙伴只是想办法解决它:

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 = url.replace(" ", "%20");
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("accept-charset", "UTF-8");
    con.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
    con.setDoOutput(true);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
    writer.write(urlParameters.toString());
    writer.close();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode == HttpStatus.SC_OK) {
        BufferedReader in = null;
        StringBuffer response = null;
        try{
            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;
}