WillxD WillxD - 1 year ago 112
Java Question

Android Emulator Connection to refused

I got this error on an Android Emulator when I tried connecting to a local server:

I/System.outīš• org.apache.http.conn.HttpHostConnectException: Connection to refused

This is the code that I used to connect to the local server (

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("");
//HttpPost httppost = new HttpPost("");
//HttpPost httppost = new HttpPost("");

try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", "Will"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("API LOGIN");

Also, I've added
<uses-permission android:name="android.permission.INTERNET" />
to the AndroidManifest.xml file. The content of my AndroidManifest.xml is:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dev.will.test" >

android:theme="@style/AppTheme" >
android:label="@string/app_name" >
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
<activity android:name=".LoginActivity" android:label="Login" />

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



There is no problem with the local server, since I can access to the url from the browser of the Android Emulator without problem and also from another computer within network, but the connection is refused from my Android application.

Please help me to figure out what can else I should configure to make it work on my app in the Android Emulator.

Answer Source

You'll need to set StrictMode before calling your server:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download