【发布时间】:2010-09-29 19:02:53
【问题描述】:
我有一个发送 HTTP POST 的简单程序。
仅在httpost.addheader("Content-Length","18") 行不存在时才有效。否则失败。在代码中,它是带有“--->”的行
注释掉这一行会使 POST 成功。
如果该行在代码中,Android 不会发送 POST 并返回协议异常错误。我使用 Wireshark 验证没有发送任何内容。
知道为什么设置 Content-Length 会产生异常吗?
代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://test.com/a_post.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
// DATA
nameValuePairs.add(new BasicNameValuePair("mydata", "abcde"));
nameValuePairs.add(new BasicNameValuePair("id","29"));
StringEntity se = new UrlEncodedFormEntity(nameValuePairs);
httppost.setEntity(se);
int seLength = (int) se.getContentLength();
String seLengthStr = Integer.toString(seLength);
httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
----> httppost.addHeader("Content-Length", "18");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String httpResponse=httpclient.execute(httppost, responseHandler);
responseV.setText(responseV.getText()+ " " + httpResponse);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
【问题讨论】:
-
堆栈跟踪表明错误是因为 Content-Length 标头已经存在。是这样吗,设置Content-Length的方法是什么?
-
为什么要手动添加 Content-Length,如果它已经存在?如果您出于某种原因需要更改它,那么它很可能是不正确的,从而导致 HTTP 错误。
-
在 HttpClient 文档中,它声明 HttpClient 为您设置 Content-length,因此您不必这样做。看了源码,HttpClient实际上是检查是否已经手动添加,如果已经存在则抛出ProtocolException
-
我也有这个问题,你解决了吗?
标签: android http-post content-length