avila
avila

Reputation: 1

Connecting to localhost in Android

I'm developing an App and have designed a bit of Frontend and backend, just the essential. And now, I want to connect both sides. First of all, I need to know how to connect to a localhost in Android.

I tried some tutorials in Internet using for example:

URL url = new URL("http://127.0.0.1");
HttpURLConnection urlConnection = (HttpURLConnection)
 url.openConnection();
try {
 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
} finally {
 urlConnection.disconnect();
}

I've tried several approaches but all of them fail. Some doesn't do anything and others stop the App showing some Zygote errors.

My question is clear. How can I connect to localhost in Android? I want a function of the style makeConnectionLocalHost() that returns whether the connection has been successful or not. Any idea why nothing works?

Upvotes: 0

Views: 1242

Answers (2)

Florian Hansen
Florian Hansen

Reputation: 816

Try instead of using "localhost" your local ip. To retrieve it, open CMD and type ipconfig. There you will find your local ip. 127.0.0.1 will create a loop back to your own device.

Upvotes: 1

Andrii Omelchenko
Andrii Omelchenko

Reputation: 13343

You can use InetAddress.getLocalHost() to get localhost address. More details here. And for HttpURLConnection you should have Web-server on this address.

Upvotes: 0

Related Questions