2013年4月23日火曜日

[AndroidSDK]DefaultHttpClientを使ってPOSTをする

public void httpConnect() {
 DefaultHttpClient client = new DefaultHttpClient();
 StringBuilder uri = new StringBuilder("hostname.com");
 HttpPost http = new HttpPost(uri.toString());

 http.setHeader("Content-type", "text/plain; charset=utf-8");
 //bodyの作成
 try {
  http.setEntity(new StringEntity("body", "UTF-8"));
 } catch (UnsupportedEncodingException e) {
  e.printStackTrace();
 }

 HttpResponse httpResponse = null;
 try {
  // HTTPリクエストを送信
  httpResponse = client.execute(http);
 } catch (Exception e) {
  e.printStackTrace();
 }

 // HTTPレスポンスを取得
 int status = httpResponse.getStatusLine().getStatusCode();
 if (HttpStatus.SC_OK == status) {
  //ヘッダーの表示
  Header[] headerArray = http.getAllHeaders();
  for (Header header : headerArray) {
   Log.d(getLocalClassName(), "header[" + header.getName() + "] [" + header.getValue() + "]");
  }
  // Bodyの取得
  HttpEntity httpEntity = httpResponse.getEntity();
  String body = null;
  try {
   body = EntityUtils.toString(httpEntity);
  } catch (ParseException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  Log.d(getLocalClassName(), "body " + body);
 } else {
  //TODO エラー処理
 }
}