2012-09-08 33 views
0

我編寫了一個Android應用程序以從本地數據庫檢索一些數據。 我創建了我的php文件,使查詢和一個類發送查詢分貝。400使用android訪問數據庫時的錯誤請求

這裏是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錯誤。 有什麼建議嗎?

+0

什麼是你發送的查詢? – alex

+0

從TAB1選擇ID – FrankBr

回答

0

如果您的數據庫位於本地計算機上,則可以嘗試使用其本地地址。將您的android設備連接到同一網絡並更改IP地址。我使用loopback(10.0.2.2)有連接問題。

您可能還需要打開本地計算機上的端口(mysql默認端口爲3306)。

對於可能的工作,在這裏檢查接受的答案的其他建議:

How to connect Android emulator with local mysql database

+0

我正在測試的本地機器Db未連接到任何路由器。 沒有其他解決方案,你建議? – FrankBr

+0

我認爲你正在模擬器上開發呢? –

+0

是的。我正在Db存在的模擬器上測試我的Android應用程序。 – FrankBr

相關問題