AndroidでHTTPリクエストを投げて処理する

作成日

2017年10月4日

サーバにどのように GET リクエストを投げてデータを取得するか,について.

HttpURLConnection

HTTP 通信を確立するために使います.DefaultHttpClient みたいなのもあるらしいです.

パーミッションの取得

これを使うためには,予めマニフェストファイルにパーミッションを追加しておく必要があります.

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

HTTP 通信部分の実装

Sample.java
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();

    // HTTP ステータスコード 200 であれば通信成功
    if (urlConnection.getResponseCode() == 200) {
        inputStream = urlConnection.getInputStream();
    }
} catch (IOException e) {
    // 失敗した時の処理
} finally {
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
    if (inputStream != null) {
        inputStream.close();
    }
}

mktia's note

Research & Engineering / Blockchain / Web Dev

© 2017-2025 mktia. All rights reserved.