如何在Android模拟器中连接localhost?

Dha*_*dra 99 localhost httpconnection android-emulator androidhttpclient

我在localhost中创建了一个php脚本,我正在连接它,httpClient但是我遇到了问题.

请告诉我如何从模拟器连接到localhost的php文件?

小智 287

使用10.0.2.2访问您的实际机器.

如您所知,当您使用模拟器时,localhost(127.0.0.1)指的是设备自己的环回服务,而不是您所期望的机器上的环回服务.

您可以使用10.0.2.2访问您的实际计算机,它是一个别名设置,以帮助开发.

  • 但是您需要先将 API 从“localhost:port”更改为“127.0.0.1:port”。之后,使用 10.0.2.2 访问您的实际机器。 (5认同)
  • 如果你想支持 API 28+ 也应该这样做:/sf/answers/3973882251/ (5认同)
  • 这可能是最好的解决方案,它不需要 AVD 上的代理配置(/sf/answers/4145215931/ 实际上也不需要)。您可以通过“http://10.0.2.2:<port_your_server_runs_on>/<path>”访问服务器上定义的端点。 (3认同)
  • 虽然这对于例如oauth没用,但是clientID仅对`localhost`有效 (2认同)
  • 10.0.2.2在使用https localhost的情况下对我不起作用,在使用https的情况下是否必须使用其他IP? (2认同)

小智 39

使用10.0.2.2作为默认AVD,使用10.0.3.2作为Genymotion

  • 应该在哪里写呢? (5认同)

Chr*_*eve 22

This is what finally worked for me.

  • Backend running on localhost:8080
  • Fetch your IP address (ipconfig on Windows)

在此处输入图片说明

  • Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080 在此处输入图片说明

  • Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)

  • 这是唯一适合我的解决方案。要点:应用程序将请求发送到与代理设置相同的 URL 和端口。 (3认同)

Md *_*ury 12

谢谢@lampShaded的回答。

在您的API / URL中直接使用,http://10.0.2.2:[your port]/并在仿真器设置下添加代理地址为10.0.2.2和端口号。有关更多信息,请访问:https : //developer.android.com/studio/run/emulator-networking.html

在此处输入图片说明


Pra*_*ash 11

感谢此博客的作者:https : //bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

在 xml 中定义网络安全配置

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>
Run Code Online (Sandbox Code Playgroud)

并设置它 AndroidManifest.xml

 <application
    android:networkSecurityConfig="@xml/network_security_config"
</application>
Run Code Online (Sandbox Code Playgroud)

为我解决了问题!

请参考:https : //developer.android.com/training/articles/security-config


jsi*_*ina 8

您应该使用以下命令更改 adb 端口:

adb reverse tcp:8880 tcp:8880; adb reverse tcp:8081 tcp:8081; adb reverse tcp:8881 tcp:8881
Run Code Online (Sandbox Code Playgroud)


Vir*_*gam 5

而不是给localhost提供IP.

  • 获取您的 IP 地址(Windows 上的 ipconfig),这里 IP 表示 IPv4,如 192.168.100.4 (2认同)