我遇到了一些麻烦,试图从客户端向服务器发送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) {
}
}
我只写了相关的代码。 我会非常感激任何关于此的帮助。 谢谢。