2014-11-02 100 views
0

我有一個應用程序,我需要從我的數據庫(MySQL和它停留在網絡上,而不是本地)獲取一些數據。我認爲一個簡單的RestFul web服務將是我訪問這個數據庫並獲取數據的最佳選擇。但是,我無法創建Web服務。我做了一些研究,但我感到困惑。我只需要訪問數據庫並從表中獲取一些數據。請給我一些幫助,以創建必要的web服務。我不希望它成爲一個複雜的Web服務。感謝大家Android應用程序的REST風格的Web服務

回答

1

這是網頁服務的php頁面。在此用戶標識符取自請求該數據的android java文件。然後從mySql中選擇數據,它將簡單地回顯所有數據,並將作爲響應提供給java文件。

seluser_profile.php

請求到Web服務
<?php 

    //$con=mysql_connect("localhost","root",""); 
    //mysql_select_db("android_db",$con); 
    $con=mysql_connect("localhost","root",""); 
    mysql_select_db("android_db",$con); 
    $uname=$_POST['userid']; 
    $q="select * from user_details where username='$uname'"; 
    $rec=mysql_query($q); 

    if(mysql_num_rows($rec)==1) 
    { 
     $arr=mysql_fetch_array($rec); 
     echo $arr[0]+" "+$arr[2]+" "+$arr[3]; 
    } 
    else 
    { 
     echo "false"; 
    } 
?> 

Java代碼。

HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php"); 

      try { 
       // Add your data 
       //Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show(); 
       List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2); 
       namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname']; 

       httppost.setEntity(new UrlEncodedFormEntity(namevpair)); 

       // Execute HTTP Post Request 
       HttpResponse response = httpclient.execute(httppost); 
       str = inputStreamToString(response.getEntity().getContent()).toString(); 
       //Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show(); 
      } catch (ClientProtocolException e) { 
       // TODO Auto-generated catch block 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
      } 

在Asynctask類的doInBackground方法中使用此java代碼。否則會給你網絡處理器異常。

private StringBuilder inputStreamToString(InputStream is) { 
      String line = ""; 
      StringBuilder total = new StringBuilder(); 
      // Wrap a BufferedReader around the InputStream 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      // Read response until the end 
      try { 
      while ((line = rd.readLine()) != null) { 
       total.append(line); 
      } 
      } catch (IOException e) { 
      e.printStackTrace(); 
      } 
      // Return full string 
      return total; 
      } 

並且還將此函數添加到來自inputstream的字符串構建中。

+0

請不要使用mysql從php查詢MySQL數據庫。它已被棄用。改用msqli代替。其次,不要像這樣從字符串中直接運行sql,因爲你會很快被黑客入侵(通過SQL注入),而是通過prepare函數來執行參數化查詢:http://php.net/manual/en/mysqli.prepare .PHP。 – 2014-11-02 18:39:51