首页 > 解决方案 > 不允许到我的本地主机的明文 HTTP 流量

问题描述

我正在使用 Volley 向我的本地主机上的地址发送 GET 请求,但它失败并出现错误:

Cleartext HTTP traffic to 192.168.1.45 not permitted

我按照这里的指南进行操作:Android 8: Cleartext HTTP traffic not allowed 并执行了以下操作:

创建了网络安全 xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">http://192.168.1.45/companyweb/greetings</domain>
    </domain-config>
</network-security-config>

在我的清单中添加了它,并且还允许明文流量:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.omerfaran.myudemyapp">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"

我仍然遇到同样的错误。从“http”更改为“https”会出现以下错误:

socket failed: EPERM (Operation not permitted)

我在 MainActivity 中的代码:

val url = "http://192.168.1.45/companyweb/greetings"
val rq = Volley.newRequestQueue(this)
val sr = StringRequest(Request.Method.GET, url, Response.Listener { response ->
    fragmentText.text = response
    Log.d("TAG", "success")
}, Response.ErrorListener { error -> Log.d("TAG", "fail" + error.toString()) })
rq.add(sr)

接下来我能做什么?

标签: androidhttpandroid-volley

解决方案


您应该只包括 IP 地址,即:

<domain includeSubdomains="true">192.168.1.45</domain>

推荐阅读