I want to make an Http Connection to my own servlet. Here is mycode:
try
{
HttpClient client = new DefaultHttpClient();
HttpPost httpMethod = new HttpPost("http://localhost:8080/getHeader/HeaderServlet");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
ResponseHandler<</span>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.HttpHostConnectionExcept ion:Connection to http://localhost:8080 refused
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. 原文地址