Search This Blog

Monday 26 August 2013

ANDROID: Connection to http://localhost:8080 refused

I wanted to make an Http Connection to my own WebServices(REST) exposed on another apache- tomcat server , but was getting this error :-
Connection to http://localhost:8080 refused
here's my code:
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:8080/RestProject/rest/hello/Details");
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream content = httpResponse.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;

}
}

i checked the exposed webservices url it was working fine from the browser , but was surprised to see that my android app was unable to access the same ,being on the same machine..

hereby im sharing the solution that resolved my problem ,hoping it would help you too,

Actually, If you are referring to a localhost from your device(emulator) than use the http://10.0.2.2/ instead of the http://127.0.0.1/ or http://localhost/.
Because your Android emulator is running on a Virtual Machine(QEMU) and you can not connect to a server directly running on your PC.

So your code snippet should be like this:
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://10.0.2.2:8080/RestProject/rest/hello/Details");
HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream content = httpResponse.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;

}
}

ie use 10.0.2.2 instead of localhost or 127.0.0.1.



6 comments:

  1. awsomeeeee ... thankzzz a lottt :)

    ReplyDelete
  2. Thanks, That is my problems. now, It's worked.

    ReplyDelete
  3. i am using the service url as "http://localhost:8080/RestProject/rest/hello/Details", but when i see in the server side tomee i see the error :
    WARNING: No operation matching request path "/RestProject/rest/hello/Details"
    why the http:// is missing?
    can you please help me in finding where can be the error?
    thanks.

    ReplyDelete
  4. Hello,
    I am testing my app in my mobile device.
    I have tried heep://127.0.0.1, http://10.0.2.2 and my pc's ip address too, but nothing is working out.
    Please help

    Thanks

    ReplyDelete
  5. I am facing the same problem as faced by Kirti.

    I am running the android app on my mobile and I am using WAMP server on my PC.

    ReplyDelete
  6. I am facing the same problem as faced by Kirti.

    I am running the android app on my mobile and I am using WAMP server on my PC.

    ReplyDelete