Reputation: 2151
I am building an android app that connects to a backend service on my laptop. It connects to a localhost address where it gets data from JSON.
It works properly when I write the IP address of my laptop in my code. This IP address can change so I would like to use the host name which doesn't seem to work.
private static final String URLLocalhost =
"http://localhost:8081/"
; // doesn't work
private static final String URLPCName ="http://PCNAME:8081/"
; // doesn't work
private static final String URLIPAddress ="http://192.168.x.y:8081/"
; // works but IP needs to be modified@Override public List<Spike> getSpikes() { RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(URLPCName).build();
I get multiple ECONNREFUSED
errors when it doesn't work.
It won't go public anytime soon so I don't have an URL for that.
I have found some solutions for this but they require making changes to my device. (haven't tried them)
I would like any device (may be limited to the local wifi) to access this service without having to change settings in the device.
How can I connect using the host name from my code?
Related question, does not solve my question: How to connect my android app to the remote web server
Upvotes: 0
Views: 4913
Reputation: 4185
Yes, AIUI, this is as expected. localhost
refers to the adapter that the Android device is using, so will route requests to the phone itself (and thus fail).
The raw IP works fine, as it's unambiguous across the devices.
http://PCNAME:8081/
depends a bit on what kind of name PCNAME
is here, and what your laptop is running. If that's a Windows machine name (using WINS) then that won't work from Android / Linux by default anyway. Switching to the FQDN, e.g. PCNAME.subdomain.mydomain.org
should probably work, but this relies on your DHCP router (or manual network setup in Android which you want to avoid) to search for that domain when unspecified, and Android respecting that routing for wireless, which I've found it doesn't (possibly this Android bug).
Probably easier to have this passed a build parameter, or have config files for debug and production settings in your build. Another simple workaround is just to reserve a static IP for your laptop using DHCP reservation or just manually specifying an IP.
Upvotes: 1