后UTF-8 EN codeD数据服务器失去某些字符 [英] Post UTF-8 encoded data to server loses certain characters

查看:104
本文介绍了后UTF-8 EN codeD数据服务器失去某些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的项目,该项目包括服务器(JavaEE的应用程序)的通信和客户端(Android应用程序)。 XML被发送作为HTTP请求(名为XML)的POST参数之一。还有,我传递给服务器的其他几个POST参数,但在功能上下面我把他们赶走的简单性。出现的问题是,某些字母不正确地传递给服务器 - 例如字符 U (请注意,这不是德国 U ,这是正确地传递,顺便说一句)。 code发送如下:

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

我的猜测是,问题出在BasicNameValuePair我用它来设置XML作为POST参数之一,它的文件说,它使用US-ASCII字符集。什么是发送UTF-8 EN codeD 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?

推荐答案

经过反复研究,并试图使事情的工作,我终于找到了问题的解决方案,这是一个简单的除现有的code。的解决办法是在UrlEn codedFormEntity类构造使用参数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");

此更改后,人物都是EN codeD并正确传送到服务器端。

After this change, characters were encoded and delivered properly to the server side.

这篇关于后UTF-8 EN codeD数据服务器失去某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆