简体   繁体   中英

HttpPost in Android - unrecognized characters

I am trying to post a message (contains both English and Chinese) to a servlet. if I use Java Application to post the message, it works well.

       public class PostText
       {
        public final static String HTTP_PORT = "...";

        public static void main(String[] args) throws Exception
        {
            String message = "...";
            System.out.println(post(message));
        }

        public static String post(String message)
        {

            HttpPost httpRequest = new HttpPost(HTTP_PORT);

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("input", message));

            try {
                httpRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

                org.apache.http.HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);


                if (httpResponse.getStatusLine().getStatusCode() == 200) {

                    String strResult = EntityUtils.toString(httpResponse.getEntity());
                    return strResult;
                } else {
                    System.out.println(httpResponse.getStatusLine().getStatusCode());
                }
            } catch (ClientProtocolException e) {
               // ...
            } catch (UnsupportedEncodingException e) {

            } catch (IOException e) {
               // ...
            }
            return null;
        }
    } 

While I use HttpPost in Android, the server will get unrecognized characters, like "æ¸å大å¦". And I tried to use HttpURLConnection to post a message, the result also contains unrecognized characters. What's the difference between HttpClient in Java Application and HttpClient in Android Application? It's very Weird.

Thanks a lot.

Problem solved. I use Wireshark to capture the packages send to the server. The header of HttpClient in the Java Application is:

User-Agent: Apache-HttpClient/4.2.1(java 1.5)

While the header of the HttpClient in the Android Application is:

User-Agent: Apache-httpclient/unavailable (java 1.4)

So I guess the version of HttpClient in android isn't the newest. from Apache HttpClient 4.1 I download a Pre-compiled.jar library and use it in my project. The Problem solved. Thanks all.

The difference may be in the way Android handles strings.

This may cause a problem if your source code is not in UTF-8: String message = "...";

I would try externalizing the string as

String message = myContext.getString(R.string.message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM