AndroidでPOSTメソッド送信をする。
注意)Android3.0からはThread使わないと実行時エラーになる
// POST送信
// 例)url=”http://www.sample.com”、param="id"、data="1234" の1個渡しの場合
public String sendPost( String url, String param , String data ) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ArrayList <NameValuePair> params = new ArrayList <NameValuePair>();
params.add( new BasicNameValuePair(param, data));
// もし項目を増やす場合は以下の行を例に真似て繰り返す
//params.add( new BasicNameValuePair("aid", "himitsu"));
HttpResponse httpresponse = null;
try {
// 送りサーバの文字コードをutf-8にセット
httppost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
// ここでサーバに送信している
httpresponse = httpClient.execute(httppost);
// ここでサーバから応答を受ける
int httpstatus =httpresponse.getStatusLine().getStatusCode();
if ( httpstatus == HttpStatus.SC_OK ) {
// サーバーから返った情報を戻り値にする
// サーバからの文字コードをutf-8にセット
return EntityUtils.toString( httpresponse.getEntity(), "UTF-8" );
}
} catch (IOException e) {
e.printStackTrace();
}
// 正常以外は全てヌルを戻り値にする
return null;
}