HttpPost UTF-8 Java编码/解码

8

我遇到了一些麻烦,试图从客户端向服务器发送utf8格式的post数据。

我已经阅读了很多关于这个主题的内容,但是我找不到解决方案。我确信我错过了一些基本的东西。

这是我的客户端代码,用于进行post请求

public static PostResponse post(String url, String data) {
        PostResponse response = new PostResponse();
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "text/plain; charset=UTF-8");

            // 3. set string to StringEntity
            StringEntity se = new StringEntity(data);

            // 4. set httpPost Entity
            httpPost.setEntity(se);

            // 5. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

        } catch (IOException e) {

        }
        return response;

    }

这是我服务器端接收UTF8文本的代码(波兰字符未显示,而是显示“?”):

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
            BufferedReader reader;
            reader = req.getReader();
            Gson gson = new Gson();
            msg = gson.fromJson(reader, MsgChat.class); //String in the client was json
        } catch (IOException e) {

        }
}

我只写了相关的代码。 我会非常感激任何关于此的帮助。 谢谢。

1
由于您下面有一些回答似乎回答了您的问题,请考虑通过单击其投票计数下方的勾选标记之一将其中一个标记为“已接受”(请参见如何接受答案?)。这显示了哪个答案对您最有帮助,并将声望点分配给答案的作者(以及您!)。这是该网站通过投票和接受答案来识别好问题和答案的想法的一部分 - Martin Schröder
3个回答

23

我遇到了同样的问题。你应该使用这段代码:

httpPost.setEntity(new StringEntity(json, "UTF-8"));

希望这能帮到你。


完美!谢谢! - JX0

1
我认为你应该使用new StringEntity(data, ContentType.APPLICATION_JSON)。默认情况下是iso-8859-1,据我了解,setHeader不是设置编码的正确方法。

0
我建议您尝试使用HttpPost的addRequestHeader方法,例如:
httpPost.addRequestHeader("Content-Type", "text/plain;charset=UTF-8");

这是向请求添加内容类型头的推荐方式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接