2014-01-27 44 views
2

我想將值傳遞給我的PHP web服務。我已經使用此代碼來傳遞「名稱」值:如何將值從android傳遞到php web服務並檢索它?

private class MyAsyncTask extends AsyncTask<String, Void, Void> { 

    protected Void doInBackground (String... params) 
    { 
      Intent intent = getIntent(); 
      String name = intent.getStringExtra("KEY_NAME"); 
      //HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://10.0.2.2/secure_login/get_data_user.php"); 

      List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1); 
      nameValuePair.add(new BasicNameValuePair("KEY_NAME", name)); 
      DefaultHttpClient hc = new DefaultHttpClient(); 
      // HttpResponse response = hc.execute(httppost); 


      try { 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
      } catch (UnsupportedEncodingException e){ 
       // writing error to log 
       e.printStackTrace(); 
      } 

      try { 
       HttpResponse response = hc.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       InputStream inStream = entity.getContent(); 
       // writing response to log 
       Log.d("Http Response:", response.toString()); 

       } catch (ClientProtocolException e) { 
        // writing exception to log 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      return null; 



    } 

而這個,用於將Stream轉換爲String。

  protected String convertStreamToString(InputStream inStream) 
      { 
       BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)); 
       StringBuilder sb = new StringBuilder(); 

       String line = null; 
       try 
       { 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
       finally 
       { 
        try 
        { 
         inStream.close(); 
        } 
        catch (IOException e) 
        { 
         e.printStackTrace(); 
        } 
       } 
       return sb.toString(); 
      } 
    } 

但我只得到了在日誌貓這樣的響應: [email protected]

我需要通過「名稱」的值,所以我的PHP Web服務可以檢索和做查詢是這樣的:

if (isset($_GET['name'])) { 
$name = $_GET['name']; 

require_once 'DB_Functions.php'; 
$db = new DB_Functions(); 
$result = mysql_query("SELECT name, email from users where name = '$name'"); 

我該如何解決?先謝謝你。

回答

0

您正在發送一個請求,並嘗試使用$_GET來檢索PHP中的參數。

嘗試通過$_POST訪問名稱變量:

if (isset($_POST['name'])) 
    $name = mysql_real_escape_string($_POST['name']); 

require_once 'DB_Functions.php'; 
$db = new DB_Functions(); 
$result = mysql_query("SELECT name, email from users where name = '$name'"); 

重要:不要忘記你把他們之前在您的SQL語句mysql_real_escape_string避免SQL注入逃脫字符串。

相關問題