4

我正在尝试将消息(包含英文和中文)发布到 servlet。如果我使用 Java 应用程序发布消息,它运行良好。

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

当我在 Android 中使用 HttpPost 时,服务器会收到无法识别的字符,例如“æ¸å大妔。我尝试使用 HttpURLConnection 发布消息,结果还包含无法识别的字符。Java 应用程序中的 HttpClient 和 Android 应用程序中的 HttpClient 有什么区别?这很奇怪。

非常感谢。

4

2 回答 2

1

问题解决了。我使用 Wireshark 来捕获发送到服务器的包。Java 应用程序中 HttpClient 的头部是:

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

而 Android 应用程序中 HttpClient 的标头是:

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

所以我猜想android中HttpClient的版本不是最新的。从Apache HttpClient 4.1 我下载了一个 Pre-compiled.jar 库并在我的项目中使用它。问题解决了。谢谢大家。

于 2012-10-19T14:17:39.247 回答
0

不同之处可能在于 Android 处理字符串的方式。

如果您的源代码不是 UTF-8 格式,这可能会导致问题: String message = "...";

我会尝试将字符串外部化为

String message = myContext.getString(R.string.message);
于 2012-10-17T07:34:28.917 回答