Home > Software design >  Accessing localhost API from android device
Accessing localhost API from android device

Time:01-26

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

CodePudding user response:

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');
  • Related