0

我编写了一个 Android 应用程序来从本地数据库中检索一些数据。我创建了我的 php 文件来进行查询和一个类来将查询发送到 db。

这是php文件:

<?php
    $db_host = "10.0.2.2";
    $db_name = " name";
    $db_user = " usr";
    $db_password = " pwd";

    //connessione al database
    $db = mysql_connect($db_host, $db_user, $db_password);

    if ($db == FALSE) die ("Errore nella connessione. Verificare i parametri nel file onnection.php");

    mysql_select_db($db_name, $db)
        or die ("Errore nella selezione del database. Verificare i parametri nel file onnection.php");

    //preleviamo la query passataci dall’applicazione
    $query = $_REQUEST['querySend'];

    //eseguiamo la query
    $result = mysql_query ($query);
    while($e=mysql_fetch_assoc($result))
    $output[]=$e;

    //stampiamo il risultato in formato json
    print(json_encode($output));
    ?>

和我的班级发送查询:

String result = "0";
InputStream is = null;

      //the query to send
      ArrayList<NameValuePair> querySend = new ArrayList<NameValuePair>();

      querySend.add(new BasicNameValuePair("querySend",query));

      //http post
      try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2/query.php");
        httppost.setEntity(new UrlEncodedFormEntity(querySend));
        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());
      }

  //convert response to string
      try{
        BufferedReader reader = new BufferedReader(
                   new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
          while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
          }
        is.close();
        result=sb.toString();

      }catch(Exception e){
        Log.e("log_tag", "Error converting result: "+e.toString());
      }

      return result;

我收到 400 错误。有什么建议么?

4

1 回答 1

0

如果您的数据库位于本地计算机上,您可以尝试使用其本地地址。将您的 android 设备连接到同一网络并更改 ip 地址。我在使用环回(10.0.2.2)时遇到了连接问题。

您可能还需要在本地计算机上打开端口(mysql 默认端口为 3306)。

对于其他可能有效的建议,请在此处查看接受的答案:

如何将Android模拟器与本地mysql数据库连接起来

于 2012-09-08T14:12:07.423 回答