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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With