Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

android - Post UTF-8 encoded data to server loses certain characters

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...