dongtuo1482 2015-02-19 05:02
浏览 489
已采纳

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 05:10
    关注

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

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部