10

I'm developing a Flutter app on a physical android device, I don't know much about networking and I'm having a trouble using an API from the phone to a local database on my laptop. I reviewed all the answers in this post

Cannot connect to localhost API from Android app

Nothing seems to work for me, I'm using Apache server on XAMPP, and the API works just fine from the laptop (127.0.0.1:8000/api/Students) but when I try to access it from the phone it doesn't work (I replaced 127.0.0.1 with the IP of my laptop which I took from ipconfig)

XAMPP control panel

when I try to access the server from the phone using laptop-IP:80 it access normally the same with laptop-IP:80/phpmyadmin XAMPP dashboard but only when my phone is connected to the laptop mobile hotspot, when I connect the two devices to the same WIFI network it shows that it's unreachable:

but when I try laptop-IP:8000/api/Students this happens:

this site can't be reached

I tried to modify Apache httpd.conf:

#Listen 12.34.56.78:80

Listen 8000      <-- Added this

from what I understood this makes the server listens to port 8000 but I'm left with the same problem

NOTE: all the pictures show my attempts to use the API on my phone's Chrome browser

1 Answer 1

18

You need to do some tweaks to the url to access it in the device as localhost is only known to the machine not the devices on which the app is running.

The urls are different for different devices

  1. Emulator
  2. Real phone (with usb debugging)

1.Emulator

static const baseUrl = "http://10.0.2.2:8000";

2.Real Device

static const baseUrl = "http://localhost:8000";
  • Additionally you need to run these command in your cmd,
      adb reverse tcp:8000 tcp:8000
    

Now your requests would go like:

 get('$baseUrl/api/Students');
Sign up to request clarification or add additional context in comments.

9 Comments

I'm still trying to test the API on Chrome before adding it to the code, it's not working on the browser in the first place
Then the question needs to be change, question says Accessing localhost API from android device to which my answer is. If your api is not working try to check the backend. and provide code where you are finding the error
the API is working fine on my laptop as I mentioned, the problem is when I try to use from a remote device
by remote device do you mean emulator or real device ?
Out of all, the adb reverse is the one which helped me !
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.