HTTPクライアント (HttpURLConnection編)
前回のあらすじ AndroidHttpClientを用いたデータ取得 - m-kawato@hatena_diary
↑ではAndroidHttpClientを使いましたが、↓この辺の記事を参考に、HttpURLConnectionを使って書き直してみました。
Y.A.M の 雑記帳: Android Apache HTTP Client と HttpURLConnection どっちを使うべき?
Android API ReferenceのHttpURLConnectionの項:
http://developer.android.com/reference/java/net/HttpURLConnection.html
割と親切なコード例が載っているので特に悩むところはありません。
基本的な構造はAndroidHttpClientを使ったサンプルから変えていませんが、インタフェースが異なるのに合わせてAsyncTaskのサブクラスのメソッドの型を変えています。あくまでAPIの使い方を確かめるのが目的なので、エラー処理はばっさり省略しています。
HttpDemo2.java
import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.AsyncTask; import android.widget.TextView; import org.apache.commons.io.IOUtils; ... public class HttpDemo2 extends Activity { TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.http_demo2); this.textView = (TextView) findViewById(R.id.text); // 接続先のURLを指定してHTTP GET実行 URL url = null; try { url = new URL("http://www.example.net:8080/"); } catch (MalformedURLException e) { e.printStackTrace(); return; } new HttpGetTask().execute(url); } // AsyncTaskのサブクラスとして、バックグラウンドでHTTP GETしてTextViewに表示するタスクを定義 class HttpGetTask extends AsyncTask<URL, Void, String> { // HttpURLConnectionを使ったデータ取得 (バックグラウンド) @Override protected String doInBackground(URL... url) { String result = ""; HttpURLConnection urlConnection = null; try { urlConnection = (HttpURLConnection) url[0].openConnection(); result = IOUtils.toString(urlConnection.getInputStream()); } catch (IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return result; } // データ取得結果のTextViewへの表示 (UIスレッド) @Override protected void onPostExecute(String response) { HttpDemo2.this.textView.setText(response); } } }