HTTP POST を送信する単純なプログラムがあります。
行が存在しない場合にのみ機能します。それ以外の場合は失敗します。コードでは、「--->」の
行です。この行をコメントアウトすると、POST が成功します。httpost.addheader("Content-Length","18")
その行がコード内にある場合、Android は POST を送信せず、Protocol Exception エラーを返します。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();
}