WillxD WillxD - 19 days ago 11
Java Question

Android Emulator Connection to http://10.0.2.2 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 http://10.0.2.2 refused


This is the code that I used to connect to the local server (http://10.0.2.2/bank/login.php):

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/bank/login.php");
//HttpPost httppost = new HttpPost("http://10.0.2.2:80/bank/login.php");
//HttpPost httppost = new HttpPost("http://10.0.2.2:8080/bank/login.php");

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");
System.out.println(e);
}


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

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

</application>

</manifest>


There is no problem with the local server, since I can access to the url http://10.0.2.2/bank/login.php 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

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

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
Comments