问题描述
我正在从事的项目包括服务器(JavaEE 应用程序)和客户端(Android 应用程序)的通信.XML 作为 HTTP 请求(名为xml")的 POST 参数之一发送.我还传递给服务器的其他 POST 参数很少,但在下面的函数中,为了简单起见,我删除了它们.出现的问题是某些字母没有正确传送到服务器 - 例如字符 Ű
(注意,这不是德语 Ü
,顺便说一下,这是正确传送的).发送代码如下:
I am working on project which includes communication of the server (JavaEE app) and client (Android app). XML is sent as one of POST parameters of the HTTP request (named "xml"). There are also few other POST parameters which I pass to server, but in function below I removed them for simplicity. Problem that occurs is that certain letters are not properly delivered to the server - for example character Ű
(Note that this is not German Ü
, which is properly delivered, by the way). Code for sending is the following:
private String postSyncXML(String XML) {
String url = "http://10.0.2.2:8080/DebugServlet/DebugServlet";
HttpClient httpclient = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("xml",XML));
UrlEncodedFormEntity form;
try {
form = new UrlEncodedFormEntity(nameValuePairs);
form.setContentEncoding(HTTP.UTF_8);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(form);
HttpResponse response = (HttpResponse) httpclient .execute(httppost);
HttpEntity resEntity = response.getEntity();
String resp = EntityUtils.toString(resEntity);
Log.i(TAG,"postSyncXML srv response:"+resp);
return resp;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
我的猜测是问题出在我用来将 XML 设置为 POST 参数之一的 BasicNameValuePair 中,它的文档说它使用 US-ASCII 字符集.发送 UTF-8 编码的 POST 字段的正确方法是什么?
My guess is that problem is in the BasicNameValuePair I use to set XML as one of POST parameters, and it's documentation says it uses US-ASCII character set. What is the proper way to send UTF-8 encoded POST fields?
推荐答案
经过大量的研究和尝试,我终于找到了解决问题的方法,那就是对现有代码进行简单的添加.解决方案是在 UrlEncodedFormEntity 类构造函数中使用参数UTF-8":
After much research and attempts to make things working, I finally found a solution for the problem, that is a simple addition to existing code. Solution was to use parameter "UTF-8" in the UrlEncodedFormEntity class constructor:
form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
在此更改后,字符被正确编码并传送到服务器端.
After this change, characters were encoded and delivered properly to the server side.
这篇关于将 UTF-8 编码的数据发布到服务器会丢失某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!