Android模拟器连接到http://10.0.2.2拒绝

时间:2015-02-19 13:02:52

标签: java php android android-studio

当我尝试连接到本地服务器时,我在Android模拟器上出现此错误:

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>

本地服务器没有问题,因为我可以毫无问题地从Android模拟器的浏览器访问网址http://10.0.2.2/bank/login.php,也可以从网络中的其他计算机访问,但是我的Android应用程序拒绝连接

请帮我弄清楚我应该配置什么才能让它在Android模拟器中的应用上运行。

1 个答案:

答案 0 :(得分:0)

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

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