我在本地机器上运行一个web服务,该服务运行在localhost:54722上。

我想从Android模拟器中运行的应用程序调用该服务。

我读到在应用程序中使用10.0.2.2将访问localhost,但它似乎不能与端口号一起工作。它说HttpResponseException: Bad Request。


当前回答

由于10.0.2.2不是Android的安全域,你必须在API 28+的网络配置中允许非安全域,默认情况下禁止非tls连接。

您可以使用我的以下配置:

在main/res/xml/network_security_config.xml中创建一个新文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

把它指向androidmanifest。xml

<application
......
......
android:networkSecurityConfig="@xml/network_security_config">

其他回答

坏请求通常意味着您发送的数据格式不正确。可能是数据映射不匹配。如果您正在收到坏请求,则意味着您能够连接到服务器,但请求没有正确发送。

我解决了服务层使用Visual Studio IIS Express时的问题。只是指向10.0.2.2:端口不会工作。我没有像其他文章中提到的那样把IIS Express搞得一团糟,而是在IIS Express前面放了一个代理。例如apache或nginx。nginx.conf看起来像

 # Mobile API
 server { 
    listen       8090;
    server_name  default_server;

    location / {
        proxy_pass http://localhost:54722;
    }
  }

然后android需要指向我的IP地址为192.168.x.x:8090

你需要设置URL为10.0.2.2:portNr

portNr = ASP给出的端口。我当前的服务在localhost上运行:3229/ service .svc

我的url是10.0.2.2:3229

我用这种方法解决了我的问题

我希望它能有所帮助……

运行您的本地主机后,您会得到http://localhost:[端口号]/在这里您可以找到您的端口号。

然后从命令中获取你的IP地址,打开你的windows命令,输入ipconfig

在我的例子中,IP是192.168.10.33,所以我的URL将是http://192.168.10.33:[端口号]/。 在Android中,工作室使用这个URL作为你的URL。然后在模拟器的手动代理中设置URL和端口号。

由于10.0.2.2不是Android的安全域,你必须在API 28+的网络配置中允许非安全域,默认情况下禁止非tls连接。

您可以使用我的以下配置:

在main/res/xml/network_security_config.xml中创建一个新文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

把它指向androidmanifest。xml

<application
......
......
android:networkSecurityConfig="@xml/network_security_config">