AndroidのWebViewでnet::ERR_CLEARTEXT_NOT_PERMITTEDエラーになったときの対策

AndroidのWebViewで以下のエラーメッセージが表示された。

ウェブページ(http://〜)は次の理由で読み込めませんでした:
net::ERR_CLEARTEXT_NOT_PERMITTED

原因は、「Android 9 Pie」から暗号化されていない接続がデフォルトで許可されなくなったため。

対策は以下の2つがある。

  • 対策1:AndroidManifest.xmlのapplicationタグに「android:usesCleartextTraffic=”true”」を追加する
  • 対策2:network_security_config.xmlを設定する

対策1:AndroidManifest.xmlのapplicationタグに「android:usesCleartextTraffic=”true”」を追加する

以下のように、AndroidManifest.xmlのapplicationタグに「android:usesCleartextTraffic=”true”」を追加する。
android:usesCleartextTrafficをtrueにすると、すべてのHTTP通信が許可される。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.gesource.example">
    <application
        android:usesCleartextTraffic="true" <-追加
    >
    </application>
</manifest>

対策2:network_security_config.xmlを設定する

以下のように、AndroidManifest.xmlのapplicationタグに「android:networkSecurityConfig=”@xml/network_security_config”」を追加する。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.gesource.example">
    <application
        android:networkSecurityConfig="@xml/network_security_config" <-追加
    >
    </application>
</manifest>

「res/xml/network_security_config.xml」ファイルを作成する。

app/
└src/
 └main/
  └res/
   └xml/
    └network_security_config.xml

「res/xml/network_security_config.xml」ファイルにHTTPでアクセスするドメイン名を登録する。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">foo.example.com</domain>
        <domain includeSubdomains="true">bar.example.com</domain>
    </domain-config>
</network-security-config>

コメントを残す

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

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください