1)报错原因:
OKHTTP3 在网络连接时对明文流量的网络请求进行了判断.
在RealConntect类中的方法connect中有这样的判断代码:
if (!Platform.get().isCleartextTrafficPermitted(host)) {
throw new RouteException(new UnknownServiceException(
"CLEARTEXT communication to " + host + " not permitted by network security policy"));
}
该判断调用的是OKHTTP框架中的AndroidPlatform中的isCleartextTrafficPermitted()方法:
@Override public boolean isCleartextTrafficPermitted(String hostname) {
try {
Class<?> networkPolicyClass = Class.forName("android.security.NetworkSecurityPolicy");
Method getInstanceMethod = networkPolicyClass.getMethod("getInstance");
Object networkSecurityPolicy = getInstanceMethod.invoke(null);
return api24IsCleartextTrafficPermitted(hostname, networkPolicyClass, networkSecurityPolicy);
} catch (ClassNotFoundException | NoSuchMethodException e) {
return super.isCleartextTrafficPermitted(hostname);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw assertionError("unable to determine cleartext support", e);
}
}
追踪发现:反射调用android系统NetworkSecurityPolicy的isCleartextTrafficPermitted(string host)来取值.
mCleartextTrafficPermitted 在 getDefaultBuilder()中可以看出大于等于Build.VERSION_CODES.P时为false
final boolean cleartextTrafficPermitted = info.targetSdkVersion < Build.VERSION_CODES.P && info.targetSandboxVersion < 2; builder.setCleartextTrafficPermitted(cleartextTrafficPermitted);
2):解决
1:targetSdkVersion 降级回到 27
2:改用 https (推荐)
3:配置xml文件 https://www.cnblogs.com/zdz8207/p/Android-28-http-https.html (本人未校验)
4: application中添加 android:usesCleartextTraffic="true"
在清单配置类 ManifestConfigSource 中: setCleartextTrafficPermitted()对mCleartextTrafficPermitted重新赋值 usesCleartextTraffic.
DefaultConfigSource(boolean usesCleartextTraffic, ApplicationInfo info) {
mDefaultConfig = NetworkSecurityConfig.getDefaultBuilder(info)
.setCleartextTrafficPermitted(usesCleartextTraffic)
.build();
}