知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
如果你嘗試使用 http 連結 OkHttp3 就拋出異常: CLEARTEXT communication to " + host + " not permitted by network security policy
開發過程中由於 https ssl 需要購買證書,費用較高,通常測試環境我們仍然使用 http 下面方法是開啟 http 模式,
創建檔案 res/xml/network_security_config.xml 內容如下
neo@MacBook-Pro ~/AndroidStudioProjects/okhttp % cat app/src/main/res/xml/network_security_config.xml <?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">localhost</domain> </domain-config> </network-security-config>
再 app/src/main/AndroidManifest.xml 檔案中增加 android:networkSecurityConfig="@xml/network_security_config"
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.netkiller.okhttp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:networkSecurityConfig="@xml/network_security_config"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> </manifest>