HTTP FAILED: java.net.ConnectException: Failed to connect to /127.0.0.1:8000

I am developing an android app in Kotlin and trying to make a request to my local Django server but getting this error.

The local server is launched on IP and port 127.0.0.1:8000 and I specified in my android application the base url - http://127.0.0.1:8000/api, but I getting this error.

I tried running it on both an emulator and a physical Android device, but I get the same result in both cases.

I checked similar questions on StackOverflow and they suggest the following solutions:

  1. Find out the IP-address and enter it in the link, I found out my IP-address (for example 192.168.0.102) and used it instead of 127.0.0.1.
  2. Start local server via 0.0.0.0:8000.
  3. Add to ALLOWED_HOSTS IP-address of your PC in setting.py.
  4. Use IP address 10.0.2.2 for android emulator.
  5. If you have a Firewall active, add an exception for port 8000. Even though I have Firewall disabled, I still added an exception for port 8000.
  6. Started the server via IP address 192.168.0.102:8000.

But when I tried all this, I got the following result:

1.

<-- HTTP FAILED: java.net.ConnectException: Failed to connect to /192.168.0.102:80

  1. Same result as number 1.

  2. Same result as number 1.

<-- HTTP FAILED: java.net.ConnectException: Failed to connect to /10.0.0.2:8000

<-- HTTP FAILED: java.net.ConnectException: Failed to connect to /10.0.0.2:80

  1. Same result as number 1.

<-- 400 Bad Request http://192.168.1.102:8000/api/register/ (284ms)

if you go to this url: http://192.168.1.212:8000/api/register/

My PC and my Android device are connected to the same Wi-Fi and I use the IP-address of my PC instead of 127.0.0.1:8000, but it gives what is indicated in the screenshot above and in point 6.

But http://127.0.0.1:8000 opens the page in the browser on my PC, but on the Android device it does not work.

First of all try running the django application with this flag:

python manage.py runserver 0.0.0.0:8000

then make sure you are allowing all host (for development only)

ALLOWED_HOSTS = ['*']

If you are having a physical device then , 10.0.2.2 will not work. You must use your PC’s local network IP instead of 127.0.0.1.

If you're on windows use command

ipconfig

if you are on mac use command

ifconfig

to find IPv4 Address (e.g., 192.168.1.100).

upade the url and try again :

val BASE_URL = "http://192.168.1.100:8000/api/"
Вернуться на верх