LoginSignup
0
0

Android Emulatorからlocalhostにアクセスする

Last updated at Posted at 2023-10-22

Android Emulatorでlocalhostにアクセスする機会はよくあると思います。
URLにhttp://localhost/を指定しただけだとエラーが出てしまいます。
そのようなときは以下の2点を確認する必要があります。

  1. http://10.0.2.2/を指定する
  2. network_security_config.xmlを設定する

http://10.0.2.2/を指定する

Android Emulatorではlocalhost(127.0.0.1)はhttp://10.0.2.2/として割り当てられています。1

開発マシンのアドレス 127.0.0.1 は、エミュレータのループバック インターフェースに対応します。開発マシンのループバック インターフェースで実行されているサービスにアクセスするには、代わりに特殊アドレス 10.0.2.2 を使用します。

そのため、localhostを指定したい場合は、http://10.0.2.2/に置き換える必要があります。

network_security_config.xmlを設定する

デフォルトでは、httpの接続は許可されていないので設定で許可する必要があります。2
res/xml/network_security_config.xmlに以下のように設定します。
ドメインのみを指定します。

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

上記の設定をAndroidManifest.xmlに指定します。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>

これでlocalhostにアクセスできるようになりました。

  1. https://developer.android.com/studio/run/emulator-networking?hl=ja#networkaddresses

  2. https://developer.android.com/training/articles/security-config?hl=ja

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0