2015-05-20 103 views
-1

Hy我正在使用android來與此php腳本進行交流:我的目標是從數據庫中提取用戶名和密碼。這是php代碼:用Android空參數發佈請求

<?php 
require 'db.php'; 
$mysqli = new mysqli("localhost", $username, $password, $database); 

if (mysqli_connect_errno()) { 
    echo "Errore in connessione al DBMS: ".mysqli_connect_error(); 
    exit(); 
} 
$username=$_POST['username']; 
$password=$_POST['password']; 
$myusername=mysql_real_escape_string($username); 
$mypassword=mysql_real_escape_string($password); 
//$mypassword=md5($password); 
$query = "SELECT userid , image FROM `utente` WHERE username='$myusername' AND password='$mypassword' LIMIT 1"; 
$result = $mysqli->query($query); 
if($result->num_rows >0) 
{ 
    while($row = $result->fetch_array(MYSQLI_ASSOC)) 
     $rows[]=$row; 
} 
header("Content-type: text/json"); 
echo json_encode($rows); 
$result->close(); 
$mysqli->close(); 
?> 

用戶名和密碼是發佈參數。我會嘗試使用URLConnection庫在android中發佈一個請求。代碼如下:

public class HTTPRequest extends AsyncTask<String, String, JSONArray> { 

    @Override 

    protected JSONArray doInBackground(String... params) { 
     URL url; 
     HttpURLConnection urlConnection = null; 
     JSONArray response = new JSONArray(); 

     try { 
      url = new URL(params[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setDoInput(true); 
      urlConnection.setDoOutput(true); 
      urlConnection.setRequestProperty("username","marco"); 
      urlConnection.setRequestProperty("password","marco"); 
      urlConnection.setRequestMethod("POST"); 


//   String username = "45dae3a1-ec1f-455a-a14b-3152001a93aa"; 
//   String password= "WSiwlK9q8Qeb"; 
//   String userpassword = username + ":" + password; 
//   String encodedAuthentication = Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP); 
//   urlConnection.setRequestProperty("Authorization", "Basic " + 
//     encodedAuthentication); 
      urlConnection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); 
      List<NameValuePair> paramskey = new ArrayList<NameValuePair>(); 
      String username="giovanni"; 
      String password="luca"; 
      paramskey.add(new BasicNameValuePair("username", username.toString())); 
      paramskey.add(new BasicNameValuePair("password", password.toString())); 
      //paramskey.add(new BasicN4ameValuePair("thirdParam", paramValue3)); 

      OutputStream os = urlConnection.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(getQuery(paramskey)); 
      //Log.i("writer",writer.toString()); 
      writer.flush(); 
      writer.close(); 
      os.close(); 
      int responseCode = urlConnection.getResponseCode(); 
      if(responseCode == HttpStatus.SC_OK){ 
       String responseString = readStream(urlConnection.getInputStream()); 
       Log.i("Risposta", responseString); 
       response = new JSONArray(responseString); 
       String responsestrings=response.toString(1);  //for debug 
       //Log.v("personalityInsightsService", responsestrings);   //for debug 
      }else{ 
       //Log.v("personalityInsightsService", "Response code:"+ responseCode); 
       return response; 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if(urlConnection != null) 
       urlConnection.disconnect(); 
     } 

     return response; 
    } 

    private String readStream(InputStream in) { 
     BufferedReader reader = null; 
     StringBuffer response = new StringBuffer(); 
     try { 
      reader = new BufferedReader(new InputStreamReader(in)); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       response.append(line); 
       //Log.i(("Risposta"),line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return response.toString(); 
    } 

    private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException 
    { 
     StringBuilder result = new StringBuilder(); 
     boolean first = true; 

     for (NameValuePair pair : params) 
     { 
      if (first) 
       first = false; 
      else 
       result.append("&"); 

      result.append(URLEncoder.encode(pair.getName(), "UTF-8")); 
      result.append("="); 
      result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); 
     } 

     return result.toString(); 
    } 
} 

在主要活動我執行這個代碼,以使該請求:

HTTPRequest httpRequest = new HTTPRequest(); 
     httpRequest.execute("http://appmuseum.altervista.org/login.php"); 
     try { 
      JSONArray httpResponse = httpRequest.get(); 
      if(httpResponse != null) 
       Log.i("STRINGA",httpResponse.toString()); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } catch (ExecutionException e) { 
      e.printStackTrace(); 
     } 
    } 

我設法與PHP腳本comunicated但之後的參數的用戶名和密碼是空的,所以jsonObject後期響應是空的。我該如何解決它?

+0

'我的目標是從數據庫中提取用戶名和密碼.'。請解釋。你的Android客戶端也在發送它們。 – greenapps

回答

1

您無法對AsyncTask實例httpRequest執行execute()和get()。刪除.execute()後的所有代碼。永遠不要做get()。添加一個onPostExecute來處理doInBackground的結果。

+0

好吧,我最好從onPostExecute獲得結果,但是這個解決方案不能解決問題;在http post請求中,參數username和password仍爲空。 –

+1

哪裏?你的腳本是一團糟。在從$ _POST數組獲得它們的值之前,您正在使用這兩個參數。 – greenapps

+0

你能編寫代碼來解決這個問題嗎?我不明白errore在哪裏。 –