我正在尝试向 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有什么区别?这很奇怪。
非常感谢。
最佳答案
问题解决了。我使用 Wireshark 捕获发送到服务器的包。 Java Application中HttpClient的header是:
User-Agent: Apache-HttpClient/4.2.1(java 1.5)
而Android应用中HttpClient的header是:
User-Agent: Apache-httpclient/unavailable (java 1.4)
所以我猜 android 中的 HttpClient 版本不是最新的。来自 Apache HttpClient 4.1我下载了一个 Pre-compiled.jar 库并在我的项目中使用它。问题解决了。谢谢大家。
关于android - Android 中的 HttpPost - 无法识别的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926613/