Rozy
Rozy

Reputation: 829

error connection refused

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

Upvotes: 57

Views: 99746

Answers (5)

Vikas Patidar
Vikas Patidar

Reputation: 43349

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.

Upvotes: 154

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.

Upvotes: 23

farhad.kargaran
farhad.kargaran

Reputation: 2373

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

Upvotes: 0

Saif Ksibi
Saif Ksibi

Reputation: 81

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");

Upvotes: 8

EboMike
EboMike

Reputation: 77752

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.)

Upvotes: 4

Related Questions