Android MySQL连接

aft*_*tab 1 android

我正在尝试使用下面的代码连接php-MySQL

try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://127.0.0.1/mytable.php");
    // HttpPost httppost = new HttpPost("http://localhost/mytable.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
}catch(Exception e){
     Log.e("log_tag", "Error in http connection"+e.toString());
}
Run Code Online (Sandbox Code Playgroud)

当控件继续httpclient.execute(httppost);时抛出异常:

org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
Run Code Online (Sandbox Code Playgroud)

我还添加<uses-permission android:name="android.permission.INTERNET" />到我的AndroidManifest.xml文件中.

当我直接从浏览器测试我的PHP文件时,它工作正常.有什么建议?

Pas*_*TIN 6

从模拟器中,如果要访问物理计算机,则必须使用以下IP地址:

10.0.2.2
Run Code Online (Sandbox Code Playgroud)

您使用的那个127.0.0.1,指向执行代码的机器 - 即模拟器本身.
由于您的Android模拟器上没有运行HTTP服务器,因此您的应用程序无法连接到它 - 这解释了您收到的错误消息.


有关更多信息,请阅读本手册的以下部分:网络地址空间