简体   繁体   English

无法通过 Android 应用访问我的笔记本电脑的本地主机

[英]Can't access my laptop's localhost through an Android app

So I did a research before posting this and the solutions I found didn't work, more precisely:所以我在发布这个之前做了一个研究,我发现的解决方案不起作用,更准确地说:

-Connecting to my laptop's IPv4 192.168.XXX.XXX - didn't work - 连接到我的笔记本电脑的 IPv4 192.168.XXX.XXX - 没有用

-Conecting to 10.0.2.2 (plus the port) - didn't work -连接到10.0.2.2 (加上端口) - 没有用

I need to test an API i built using Django Rest framework so I can get the json it returns, but i cant access through an Android app i'm building (I'm testing with a real device, not an emulator).我需要测试我使用 Django Rest 框架构建的 API,以便我可以获得它返回的json ,但我无法通过我正在构建的 Android 应用程序访问(我正在使用真实设备进行测试,而不是模拟器)。 Internet permissions are set on Manifest and i can access remote websites normally.互联网权限在清单上设置,我可以正常访问远程网站。 Just can't reach my laptop's localhost(they are in the same network)只是无法访问我的笔记本电脑的本地主机(它们在同一个网络中)

I'm pretty new to Android and Python and Django as well (used to built Django's Rest Framework API).我对 Android、Python 和 Django 也很陌生(用于构建 Django 的 Rest Framework API)。

EDIT: I use localhost:8000/snippets.json or smth like this to connect on my laptop.编辑:我使用localhost:8000/snippets.json或这样的 smth 来连接我的笔记本电脑。

PS: I read something about XAMP server... do I need it in this case? PS:我读了一些关于 XAMP 服务器的内容......在这种情况下我需要它吗?

Thanks in advance提前致谢

Have you started the server like this?你是这样启动服务器的吗?

python manage.py runserver 0.0.0.0:8000

Then, try to connect to 192.168.XXX.XXX:8000然后,尝试连接到 192.168.XXX.XXX:8000

I tried the above, but failed to work in my case.我尝试了上述方法,但在我的情况下未能奏效。 Then with running python manage.py runserver 0.0.0.0:8000 I also had to add my IP to ALLOWED_HOSTS in settings.py, which solved this issue.然后通过运行 python manage.py runserver 0.0.0.0:8000 我还必须将我的 IP 添加到 settings.py 中的 ALLOWED_HOSTS,这解决了这个问题。

eg.例如。 Add your ip to allowed hosts in settings.py ALLOWED_HOSTS = ['192.168.XXX.XXX']在 settings.py ALLOWED_HOSTS = ['192.168.XXX.XXX'] 中将您的 IP 添加到允许的主机

Then run the server python manage.py runserver 0.0.0.0:8000然后运行服务器 python manage.py runserver 0.0.0.0:8000

Others have already given the answer but those solutions didn't work for me when I was running Django server on Ubuntu and was trying to access it from my Mobile app.其他人已经给出了答案,但是当我在 Ubuntu 上运行 Django 服务器并尝试从我的移动应用程序访问它时,这些解决方案对我不起作用。

Following is what worked for me:以下是对我有用的内容:

Step 1: Run server to access it from your IP第 1 步:运行服务器以从您的 IP 访问它

python manage.py runserver 0.0.0.0:8000

Step 2: Open port in firewall (Missing step in above given answers - Needed for Ubuntu)第 2 步:在防火墙中打开端口(上面给出的答案中缺少步骤 - Ubuntu 需要)

$ sudo ufw enable 
$ sudo ufw allow 8000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM