Android Emulator连接到http://10.0.2.2拒绝


Android Emulator Connection to http://10.0.2.2 refused

当我尝试连接到本地服务器时,我在Android Emulator上遇到了这个错误:

I/System.out﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2 refused

这是我用来连接到本地服务器的代码(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);
}

此外,我已经将<uses-permission android:name="android.permission.INTERNET" />添加到AndroidManifest.xml文件中。我的AndroidManifest.xml的内容是:

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

本地服务器没有问题,因为我可以访问urlhttp://10.0.2.2/bank/login.php从Android Emulator的浏览器,也从网络中的另一台计算机,没有问题,但我的Android应用程序拒绝了连接。

请帮我弄清楚我还可以配置什么,以便在Android Emulator中的应用程序上运行。

在调用服务器之前,您需要设置StrictMode:

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