![](/img/trans.png)
[英]Android Studio error org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
[英]Android Emulator Connection to http://10.0.2.2 refused
我尝试连接到本地服务器时在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模拟器的浏览器访问url http://10.0.2.2/bank/login.php而没有问题,也可以从网络中的另一台计算机访问,但连接是拒绝了我的Android应用程序。
请帮我弄清楚我应该配置什么以使其在Android模拟器中的应用程序上运行。
在调用服务器之前,您需要设置StrictMode:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.