Question
When using OkHttp to request an http address on Android 9.0 mobile phones, the following error will be reported:
java.net. UnknownServiceException: CLEARTEXT communication to **** not permitted by network security policy
The reason is that after Android 9.0, Google officially explained:
In order to ensure the security of user data and devices, Google will require encrypted connections by default for applications of the next generation Android system (Android P), which means that
Android P will prohibit apps from using all unencrypted connections. Therefore, Android devices running Android P
systems will not be able to send or receive traffic plainly in the future.
Solutions (Three Methods):
- APP change to https request
- argetSdkVersion lowered to below 27 change
- Network security configuration
The Third Method
Create an xml folder under the res folder, then create a network_security_config.xml file in the xml directory with the following contents:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
Add properties to the application tag under the AndroidManifest.xml file
android:networkSecurityConfig="@xml/network_security_config"
After configuration, you can access the http address.