HttpPost on Android - unrecognized characters

I am trying to send a message (containing both English and Chinese) to a servlet. if I use a Java application to post a post, 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; } } 

As long as I use HttpPost on Android, the server will receive unrecognized characters, for example "æ¸Γ₯Γ₯€§Γ₯ |". And I tried using HttpURLConnection to post a message, the result also contains unrecognized characters. What is the difference between HttpClient in a Java application and HttpClient in an Android application? It is very strange.

Thank you very much.

+4
source share
2 answers

The problem is resolved. I use Wireshark to capture packets sent to the server. HttpClient header in Java application:

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

So far, the HttpClient header in the Android app:

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

So, I assume that the version of HttpClient in android is not the newest. from Apache HttpClient 4.1 I download the Pre-compiled.jar library and use it in my project. The problem is resolved. Thanks to everyone.

+1
source

The difference may be in how 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); 
0
source

Source: https://habr.com/ru/post/1440193/


All Articles