我有一个发送 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();
}