"Cleartext HTTP traffic to www.android.com not permitted" 在 Android Studio 中尝试 httpurlconnection 时

"Cleartext HTTP traffic to www.android.com not permitted" when trying httpurlconnection in Android Studio

我在标题行中收到错误。我试图通过尝试我在堆栈溢出时发现的建议来克服它,包括添加到 AndroidManifest.xml this:

android:networkSecurityConfig="@xml/network_security_config"

然后创建 res/xml/network_security_config.xml 包含以下内容:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">www.android.com</domain>
</domain-config>
</network-security-config>

参考Activity中的调用代码如下:

try {
       url = new URL("http://www.android.com/");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
   

但到目前为止运气不好。我的目标是在这里建立一个简单的连接作为测试。如何解决这个问题? TIA.

将此添加到您的应用程序

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
        <application
            ...
            android:usesCleartextTraffic="true" // this line.
            ...>
            ...
        </application>
 </manifest>