HTTPS GET の実行
〜 Android Studio の使い方 21 〜
2025-02-21 作成 福島
TOP > androidstudio > httpsget

使用ツール

    Android Studio Flamingo | 2022.2.1 Patch 2  


1. 通常のプロジェクトを作成する。

「Empty Activity」「Empty Views Activity」等のプロジェクトが対象。
ここでは画面を操作しないので「No Activity」でも構わないが、
画面を使用しない Android プログラムは無いと思われるので、ここでは割愛する。(選択しない)


2. マニフェストの記述。

マニフェストファイルに通信機能を使用する宣言を記述する。
要素名内容備考
マニフェスト Android  >  app  >  manifests  > AndroidManifest.xml-
要求機能android.permission.INTERNETインターネットへのアクセス

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application

        //~ 省略 ~

    </application>

</manifest>


3. MainActivity.java を編集

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


// 非同期ジョブの作成と実行 String URL = "https://icanhazip.com/"; // I can has IP: グローバルIPを返してくれるサイト HttpsGet httpsGet = new HttpsGet(URL); httpsGet.execute(); // 非同期ジョブの終了を待つ while(! httpsGet.isDone()) { try { sleep(100); } catch (Exception ignored) {} // ただの Wait } // 結果を取得する String strData = httpsGet.getStrData(); Log.d("HttpsGet",strData);
}
// 非同期ジョブの定義(クラス) static class HttpsGet { ExecutorService executorService; boolean done; String url,strData; // コンストラクタ public HttpsGet(String url) { done = false; executorService = Executors.newSingleThreadExecutor(); this.url = url; strData = null; } // スレッド実行部を定義 class HttpsRunnable implements Runnable { @Override public void run() { strData = httpsGetProc(url); done = true; executorService.shutdown(); } } // スレッドを実行する void execute() { executorService.submit(new HttpsRunnable()); } // スレッドの終了を確認する boolean isDone() { return done; } // 取得したデータを返す String getStrData() { return strData; } } // HTTPS GET の実行部 - 非同期ジョブの中で実行させる // (HttpsURLConnection は非同期ジョブの外で動作しない) static String httpsGetProc(String targetUrl) /*throws Exception*/ { // データ保存バッファを作成 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { // クライアント接続子を作成 (https GET) URL url = new URL(targetUrl); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setRequestMethod("GET"); httpsURLConnection.connect(); // 対象サーバに接続する // データ入力バッファを作成 (入力元はクライアント接続子) InputStream inputStream = httpsURLConnection.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); // データ保存バッファにデータを読み込む (バイナリ処理なので改行文字もデータとして読み込む) while(true) { byte[] tmpBuf = new byte[8192]; int readLen = bufferedInputStream.read(tmpBuf,0,tmpBuf.length); // *1 if(readLen <= 0) break; byteArrayOutputStream.write(tmpBuf,0,readLen); // *1 } // データ入力バッファ、保存バッファをクローズ bufferedInputStream.close(); inputStream.close(); // 対象サーバとの通信を切断 httpsURLConnection.disconnect(); } catch (Exception ignored) {} // サンプルなので例外を無視している*2 // 取得データを文字列として返す return byteArrayOutputStream.toString(); }
}
*1….read()、….write() で記述している  off: 0 は、ともに tmpBuf[] の offset を示している。C 言語で例えると「(char* )tmpBuf + 0」。
*2本来なら例外処理を記述すべきだが、ここでは可読性を優先して例外を無視している。
呼び出し元に例外を throw するなら、関数宣言の「throws Exception」を有効にする。