向服务器发布UTF-8编码的数据会丢失某些字符

我正在从事包括服务器(JavaEE应用程序)和客户端(Android应用程序)通信的项目。 XML作为HTTP请求(名为“xml”)的POST参数之一发送。 我传递给服务器的其他POST参数也很less,但在下面的函数中,为了简单起见,我将它们移除了。 发生的问题是某些字母没有正确地传送到服务器 – 例如字符Ű (请注意,这不是德文,顺便说一下,它是正确传送的)。 代码发送如下:

 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; } 

我的猜测是问题出在BasicNameValuePair中,我使用它来将XML设置为POST参数之一,它的文档说它使用US-ASCII字符集。 发送UTF-8编码的POST字段的正确方法是什么?

经过大量的研究,并试图使事情工作,我终于find了解决这个问题,这是现有的代码简单的补充。 解决方法是在UrlEncodedFormEntity类构造函数中使用参数“UTF-8”:

 form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8"); 

在这个改变之后,字符被编码并正确地传送到服务器端。

当你做这条线

 form = new UrlEncodedFormEntity(nameValuePairs); 

你需要像这样指定字符集

 form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8"); 

你可以去Android Developer找出来。

用参数列表构造一个新的UrlEncodedFormEntity,默认编码为DEFAULT_CONTENT_CHARSET

 String finalString = URLEncoder.encode(request, "UTF-8"); return finalString; 

在你的post方法中用户finalString。

或者我可以在我的test2.jspx的顶部scriptlet中添加下面的代码,这将解决这个问题

 String en = request.getCharacterEncoding(); if(en == null) { request.setCharacterEncoding("UTF-8"); } 

我也面临类似的问题。 但为了validation,我在下面写了两个JSP

————- test1.jspx —————–

 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <jsp:directive.page contentType="text/html; charset=utf-8"/> <body> <form action="/test2.jspx" method="POST" accept-charset="UTF-8"> <input type="text" name="u" id="u" /> <input type="submit" value="Login3" /> </form> </body> </html> -------------test2.jspx----------------- <html xmlns="http://www.w3.org/1999/xhtml" xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0"> <jsp:directive.page contentType="text/html; charset=utf-8"/> <body> The test entered is <jsp:expression>request.getParameter("u")</jsp:expression> </body> </html> ---------------------------------- 

然后在第一个input框中input重音字符下面的字母表中

而且这个问题清晰可见,Android浏览器无法在POST参数中处理UTF-8编码。

我想,我将需要使用GET方法,并需要在tomcat server.xml中为连接器添加“URIEncoding = UTF-8”。

这是从Android发送UTF-8数据的问题。 你的代码将工作得很好,除了你将不得不把你的String编码到Base64 。 在服务器PHP你只是解码Base64string。 它为我工作。 我可以分享,如果你需要的代码。