dongtuo1482
2015-02-19 13:02
浏览 456

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

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.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • douan4359 2015-02-19 13:10
    最佳回答

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

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题