android Logcat报错 CLEARTEXT communication to 192.168.1.2 not permitted by network security policy

Previous projects were debugged on the emulator. These days, I used the real machine to debug. Because the android version of the emulator was very low, all the errors were useless. My phone’s android version was Android10, so I made an error. Call okhttp is useless to return data, and there is nothing in my interface. Then check the Logcat information
Logcat information:
Insert picture description here
Reason: Android P restricts network requests for plaintext traffic, and non-encrypted traffic requests will be banned by the system.
If the request of the current application is a htttp request instead of https, this will lead the system to prohibit the current application from making the request. If the url of WebView uses the http protocol, the loading failure will also occur, and https will not be affected.

For this reason, OkHttp3 has done a check, so if plaintext traffic is used, by default, Android P version OkHttp3 will throw an exception: CLEARTEXT communication to "+ host +" not permitted by network security policy

if (!Platform.get().isCleartextTrafficPermitted(host)) {
    
    
      throw new RouteException(new UnknownServiceException(
          "CLEARTEXT communication to " + host + " not permitted by network security policy"));
 }

Solution: Create a new file network_security_config.xml file
in the res new folder xml

<?xml version ="1.0" encoding ="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

Configure android:networkSecurityConfig="@xml/network_security_config" in the AndroidMainfest.xml folder

 <application
        android:name=".common.MyApplication"
        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/MainTheme" android:networkSecurityConfig="@xml/network_security_config">

problem solved

Guess you like

Origin blog.csdn.net/rj2017211811/article/details/107266598