如何在 Android 模拟器中连接 localhost?
我在 localhost 中创建了一个 php 脚本,并将其与 httpClient
连接,但我遇到了问题。
请告诉我如何从模拟器连接到 localhost 上的 php 文件?
I have made a php script inside localhost and I am connecting that with httpClient
but I am getting a problem.
Please tell me how can I connect to a php file at localhost from the emulator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
10.0.2.2
访问您的实际计算机。如您所知,当您使用模拟器时,
localhost
(127.0.0.1
) 指的是设备自己的环回服务,而不是您所期望的计算机上的环回服务。您可以使用 10.0.2.2 来访问您的实际机器,它是为帮助开发而设置的别名。
Use
10.0.2.2
to access your actual machine.As you've learned, when you use the emulator,
localhost
(127.0.0.1
) refers to the device's own loopback service, not the one on your machine as you may expect.You can use 10.0.2.2 to access your actual machine, it is an alias set up to help in development.
默认 AVD 使用
10.0.2.2
,Genymotion 使用10.0.3.2
Use
10.0.2.2
for default AVD and10.0.3.2
for Genymotion谢谢@lampShaded 的回答。
在您的 API/URL 中直接使用
http://10.0.2.2:[your port]/
并在模拟器设置下添加代理地址 10.0.2.2 和端口号。有关更多信息,您可以访问:https://developer.android.com/studio/ run/emulator-networking.htmlThanks, @lampShaded for your answer.
In your API/URL directly use
http://10.0.2.2:[your port]/
and under emulator setting add the proxy address as 10.0.2.2 with the port number. For more, you can visit: https://developer.android.com/studio/run/emulator-networking.html这最终对我有用。
将 Android 模拟器的代理配置为使用您的 IP 地址作为主机名,并将运行后端的端口作为端口(在我的情况:192.168.1.86:8080
让您的 Android 应用程序向同一 URL (192.168.1.86:8080) 发送请求(向 localhost 发送请求,以及 http://10.0.2.2 对我不起作用)
This is what finally worked for me.
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)
感谢此博客的作者: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/
在 xml 中定义网络安全配置
并将其设置在
AndroidManifest.xml
为我解决了问题!
请参考:https://developer.android.com/training/articles/security-config< /a>
Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/
Defining network security config in xml
And setting it on
AndroidManifest.xml
Solved issue for me!
Please refer: https://developer.android.com/training/articles/security-config
您应该使用以下命令更改 adb 端口:
you should change the adb port with this command:
不要给 localhost,而是给 IP。
Instead of giving localhost give the IP.