(29) AndroidEmulatorからHTTP接続する。

投稿者: | 2022年11月30日

592 views

この記事は最終更新から 741日 が経過しています。

1. やりたいこと

やりたいことが三つある。

【1番目】AndroidEmulator上で動作するアプリから、インターネット上の Webサイトに HTTPSアクセスしたい。
【2番目】AndroidEmulator上で動作するアプリから、LAN上&他マシン上の Webサイトに HTTPアクセスしたい。
【3番目】AndroidEmulator上で動作するアプリから、同一マシン上の Webサイトに HTTPアクセスしたい。

2. やってみた

【1番目】~【3番目】で相違点は僅か、気にするほどの違いはなかった。

【1番目】インターネット上の Webサイトに HTTPSアクセス

(1) INTERNETアクセスを許可する。

AndroidManufest.xml に 4行目を追記する。

<?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
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"

(2) HTTPS接続を強制する。(必要な場合)

新規に XMLファイルを作成する。名前は何でもよい。
ここでは communication_rules.xml として作成し、/res/xml フォルダに配置した。

手順:
1. xmlフォルダを選択する。
2. 右クリックして popup menuを表示する。
3. [New]-[File]メニューを選択する。
4. ファイル名 communication_rules.xml を入力する。

<network-security-config>
    <domain-config usesCleartextTraffic="false">
        <domain includeSubdomains="true">www.dogrow.net</domain>
    </domain-config>
</network-security-config>

次に、作ったファイルを AndroidManufest.xml でインポートする。7行目を追記する。

<?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" />
    <!-- android:usesCleartextTraffic="true" -->
    <application
        android:networkSecurityConfig="@xml/communication_rules"
        android:allowBackup="true"
 :

(3) Gradleに OkHTTPパッケージを追加

Gradleはスクリプトを書いてビルド実行を制御するツール。
今回は OkHttpをインポートして使う。

build.gradle.
7行目を追記する。

dependencies {
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
}

記述後は、Sync now メニューを選択し、パッケージのダウンロードを実行する。

(4) プログラム中で HTTPリクエストを発行

以下の機能を持つ Javaプログラムを書いた。
1) URLを指定し、HTTPリクエストを発行する。
2) HTTPレスポンスから、サーバー側が出力した文字列を取得し、デバッグログに表示する。

public void sendHttpGet(){
    try{
        sendHttpReq("http://www.dogrow.net/MyAPP");
    }catch(Exception e){
        Log.e("MyAPP", e.getMessage());
    }
}

private void sendHttpReq(String url) throws IOException{
    OkHttpClient c = new OkHttpClient();
    Request req = new Request.Builder().url(url).build();
    c.newCall(req).enqueue(new Callback(){
        @Override
        public void onResponse(@NotNull Call call, @NotNull Response resp) throws IOException{
            Log.d("MyAPP", resp.body().string());
        }
        @Override
        public void onFailure(@NotNull Call call, @NotNull IOException e){
            Log.e("MyAPP", e.getMessage());
        }
    });
}

【2番目】LAN上&他マシン上の Webサイトに HTTPアクセス

上記の【1番目】からの変更点のみを記す。

(1) 通信情報を設定する。

communication_rules.xml を書き換える。

3行目: 非セキュアな HTTP 接続も許可する。
これを指定しないと、HTTPSでない場合に以下のエラーが発生する。

CLEARTEXT communication to 192.168.2.39 not permitted by network security policy

3行目: 平文(非セキュアなHTTP)での通信を許可する。
4行目: 接続を許可するIPアドレスもしくはホスト名を指定する。

<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.2.39</domain>
    </domain-config>
</network-security-config>

【3番目】同一マシン上の Webサイトに HTTPアクセス

上記の【2番目】からの変更点のみを記す。

(1) 通信情報を設定する。

communication_rules.xml を書き換える。

4行目: 接続を許可するホスト名に localhost を指定する。(127.0.0.1 or LAN上のIPアドレスでよい)

<?xml version="1.0" encoding="utf-8" ?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)