error connection refused

Android

Android Problem Overview


I want to make an Http Connection to my own servlet. Here is my code:

try
{
    HttpClient client = new DefaultHttpClient();
    HttpPost httpMethod = new HttpPost("http://localhost:8080/getHeader/HeaderServlet");
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String response = client.execute(httppost, responseHandler);
    String result = response.toString();
}

But i'm unable to, and I get the error:

org.apache.http.conn.HttpHostConnectionException:Connection to http://localhost:8080 refused

I will be thankful your help

Android Solutions


Solution 1 - Android

Use 10.0.2.2 instead of localhost.

If you are referring to a localhost from your device 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 will be like this:

HttpPost httpMethod = new HttpPost("http://10.0.2.2:8080/getHeader/HeaderServlet");

Refer this : Emulator Networking for more information.

Solution 2 - Android

I had the same problem but I solved it by putting in the following label said

<uses-permission android:name="android.permission.INTERNET" />

which allowed me to connect to the Internet.

Solution 3 - Android

The better is that you put your PC LAN's IP , for example , in windows , run "ipconfig" in a cmd console , suppose that your IP is : 192.168.1.34 , then

HttpPost httpMethod = 
   new HttpPost("http://192.168.1.34:8080/getHeader/HeaderServlet");

Solution 4 - Android

localhost would be the Android device itself. I assume that this is not where your servlet is. You'll need to enter the hostname or IP of wherever your servlet is.

(If it's really on your device (why?!), then you need to make sure you have the INTERNET permission. You could try connecting to it from the built-in browser.)

Solution 5 - Android

For me problem solved by deleting proxyHost,proxyPort, etc from gradle.properties

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRozyView Question on Stackoverflow
Solution 1 - AndroidVikas PatidarView Answer on Stackoverflow
Solution 2 - AndroidJesús Antonio CabarcasView Answer on Stackoverflow
Solution 3 - AndroidSaif KsibiView Answer on Stackoverflow
Solution 4 - AndroidEboMikeView Answer on Stackoverflow
Solution 5 - Androidfarhad.kargaranView Answer on Stackoverflow