[Solved] Android OkHttp Error: java.net.UnknownServiceException


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):

  1. APP change to https request
  2. argetSdkVersion lowered to below 27 change
  3. 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"?>
    <base-config cleartextTrafficPermitted="true" />

Add properties to the application tag under the AndroidManifest.xml file


After configuration, you can access the http address.

Read More: