【Android】HTTP通信でGET/POSTをする方法

HTTP通信でデータをGET/POSTをする場合の処理です。

HTTP通信をする場合、非同期処理をしないといけないので注意して下さい。

GET


HttpClient client = new DefaultHttpClient();

// パラメータの設定
ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
value.add( new BasicNameValuePair("key1", "value1"));
value.add( new BasicNameValuePair("key2", "value2"));
value.add( new BasicNameValuePair("key3", "value3"));

String responseData = null;

 try {
    String query = URLEncodedUtils.format(value, "UTF-8");
    HttpGet get = new HttpGet("URL" + "?" + query);

    // リクエスト送信
    HttpResponse response = client.execute(get);
    // 取得
    HttpEntity entity = response.getEntity();
    responseData = EntityUtils.toString(entity, "UTF-8");
} catch(IOException e) {
    e.printStackTrace();
}

POST


HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("URL");

// パラメータの設定
ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
value.add( new BasicNameValuePair("key1", "value1"));
value.add( new BasicNameValuePair("key2", "value2"));
value.add( new BasicNameValuePair("key3", "value3"));

String responseData = null;

try {
    post.setEntity(new UrlEncodedFormEntity(value, "UTF-8"));// 文字コード変換
    // リクエスト送信
    HttpResponse response = client.execute(post);
    // 取得
    HttpEntity entity = response.getEntity();
    responseData = EntityUtils.toString(entity, "UTF-8");
} catch(IOException e) {
    e.printStackTrace();
}

参考サイト:

Androidでサーバと通信する方法(Asynctaskによる非同期HTTP通信) | Tech Booster

プログラム備忘録 Android での POST 送信

Android:HTTP通信でGET, POSTする | 自転車で通勤しましょ♪ブログ

電気羊はandroidの夢を見る: HttpGet/Postにパラメータを渡す