Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error connection refused

Tags:

android

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

like image 752
Rozy Avatar asked Feb 05 '11 05:02

Rozy


2 Answers

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.

like image 180
Vikas Patidar Avatar answered Oct 17 '22 22:10

Vikas Patidar


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.

like image 43
Jesús Antonio Cabarcas Avatar answered Oct 17 '22 22:10

Jesús Antonio Cabarcas