LoginSignup
130
95

More than 3 years have passed since last update.

Android 9(Pie)でHTTP通信を有効にする

Last updated at Posted at 2018-08-09

Android 9(Pie)でデフォルトでHTTPS通信になったので(App Transport Security(以下ATS)みたいな感じ)、HTTP通信を許可する方法を書いておく。
時代の流れ的にはHTTPS対応する方向がベターだと思う。

ATSのような全許可の仕組みは無い(たぶん)。

エラー

これまで通り通信しようとすると、以下のようなエラーが表示される。

java.io.IOException: Cleartext HTTP traffic to example.com not permitted

対応

res/xmlディレクトリを掘って、以下のようなファイルを置く。

res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">example.com</domain>
    </domain-config>
</network-security-config>
  • example.com部分が対象のドメインなので適宜書き換える。
  • cleartextTrafficPermitted="true"がHTTP平文通信を許可する設定(ATSのNSTemporaryExceptionAllowsInsecureHTTPLoadsのようなもの)。
  • includeSubdomains="true"はサブドメインを含む場合に記載(ATSのNSIncludesSubdomainsのようなもの)。

作った設定をAndroidManifestから参照させる。

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

これでHTTP通信できるようになる。

トラブルシュート

設定後に以下のようなメッセージが表示されている場合は、ファイルの場所に問題があるかAndroidManifestファイルの記載内容に問題があって設定ファイルを読み込めていない。

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

読み込みがうまくいっている場合は以下のような表示になる。

D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config

参考

130
95
9

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
130
95