用android访问数据库时400 Bad Request

I coded an Android app to retrieve some data from a local database. I created my php file to make the query and a class to send the query to db.

Here is the php file:

<?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));
    ?>

and my class to send the query:

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 + "
");
          }
        is.close();
        result=sb.toString();

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

      return result;

I get a 400 error. Any suggestions?

In case your database is on a local machine you could try using its local address instead. Connect your android device to the same network and change the ip address. I've had connection problems using the loopback(10.0.2.2).

You might need to open ports on your local machine aswell (mysql default port is 3306).

For other suggestions that might work, check accepted answer here:

How to connect Android emulator with local mysql database