Mbm*_*Mbm 6 java servlets httpclient utf-8
我在尝试将utf8格式的发布数据从客户端发送到我的服务器时遇到了麻烦.
我已经阅读了很多关于这个主题但我找不到解决方案.我确信我遗漏了一些基本的东西.
这是我发布帖子请求的客户端代码
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;
}
Run Code Online (Sandbox Code Playgroud)
这是我服务器端的代码,用于接收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) {
}
}
Run Code Online (Sandbox Code Playgroud)
我只写了相关的代码.
我将不胜感激任何帮助.谢谢.
Vie*_*ran 12
我有同样的问题.您应该使用此代码:
httpPost.setEntity(new StringEntity(json, "UTF-8"));
Run Code Online (Sandbox Code Playgroud)
希望这可以帮到你.
据我所知你应该使用new StringEntity(data, ContentType.APPLICATION_JSON). 默认情况下iso-8859-1,setHeader据我所知,这不是设置编码的正确方法。
| 归档时间: |
|
| 查看次数: |
10954 次 |
| 最近记录: |