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

dst*_*nox 42 xml android utf-8 special-characters

我正在开发项目,其中包括服务器(JavaEE app)和客户端(Android app)的通信.XML作为HTTP请求的POST参数之一发送(名为"xml").我传递给服务器的其他POST参数也很少,但在下面的功能中,为了简单起见,我删除了它们.出现的问题是某些字母未正确传送到服务器 - 例如字符?(请注意,这不是德语Ü,顺便说一下,它是正确传送的).发送代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

dst*_*nox 100

经过大量的研究和尝试使事情有效,我终于找到了解决问题的方法,这是对现有代码的简单补充.解决方案是在UrlEncodedFormEntity类构造函数中使用参数"UTF-8":

form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Run Code Online (Sandbox Code Playgroud)

在此更改之后,字符被编码并正确传送到服务器端.

  • 阅读以下帖子是研究:p nice :) (8认同)

Bob*_*Gao 21

当你这样做的时候

form = new UrlEncodedFormEntity(nameValuePairs);
Run Code Online (Sandbox Code Playgroud)

你需要像这样指定字符集

form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
Run Code Online (Sandbox Code Playgroud)

你可以去Android Developer了解一下.

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