2013-05-14 86 views
17

我想從android應用程序中的Web服務器檢索數據,並且不知道從哪裏開始。我應該使用網絡服務嗎?如何在android應用程序中從Web服務器獲取數據?

+1

那是一個非常通用的問題,但我已經發布了一個答案,其中包括鏈接到三個教程從開始覆蓋準確完成這一過程 – o0rebelious0o 2013-05-14 15:07:51

+1

嗯,正要用確切的措辭提出一個問題。看起來對我來說既清晰又有用! – 2015-05-25 16:41:32

+2

「由查爾斯,比爾蜥蜴關閉不是一個真正的問題」這個網站變得越來越荒謬.. – AlwaysConfused 2016-04-22 14:24:07

回答

24

我會推薦這些教程:

Connect android with PHP and MySqlJSON in androidPHP and MySQLi

我用這些教程和管理,以得到你正在嘗試做的不會有太大困難工作。

他們之間描述瞭如何在每個階段,android應用程序,數據庫和web服務器端進行嘗試的每一個步驟,並且包含額外的信息,以便您可以隨後處理和使用收到的信息信息

我會補充的唯一的事情是連接Android與PHP和MySql教程使用mysql_在PHP中已棄用。更好地使用MySqli,這就是我包括第三個鏈接的原因。

你想要做什麼的基本輪廓是這樣的:

1)在Android應用讓使用類像這樣的服務器PHP腳本的請求:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONParser { 

    // Response from the HTTP Request 
    static InputStream httpResponseStream = null; 
    // JSON Response String to create JSON Object 
    static String jsonString = ""; 

    // Method to issue HTTP request, parse JSON result and return JSON Object 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     try { 
      // get a Http client 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      // If required HTTP method is POST 
      if (method == "POST") { 
       // Create a Http POST object 
       HttpPost httpPost = new HttpPost(url); 
       // Encode the passed parameters into the Http request 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 
       // Execute the request and fetch Http response 
       HttpResponse httpResponse = httpClient.execute(httpPost); 
       // Extract the result from the response 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       // Open the result as an input stream for parsing 
       httpResponseStream = httpEntity.getContent(); 
      } 
      // Else if it is GET 
      else if (method == "GET") { 
       // Format the parameters correctly for HTTP transmission 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       // Add parameters to url in GET format 
       url += "?" + paramString; 
       // Execute the request 
       HttpGet httpGet = new HttpGet(url); 
       // Execute the request and fetch Http response 
       HttpResponse httpResponse = httpClient.execute(httpGet); 
       // Extract the result from the response 
       HttpEntity httpEntity = httpResponse.getEntity(); 
       // Open the result as an input stream for parsing 
       httpResponseStream = httpEntity.getContent(); 
      } 
      // Catch Possible Exceptions 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      // Create buffered reader for the httpResponceStream 
      BufferedReader httpResponseReader = new BufferedReader(
        new InputStreamReader(httpResponseStream, "iso-8859-1"), 8); 
      // String to hold current line from httpResponseReader 
      String line = null; 
      // Clear jsonString 
      jsonString = ""; 
      // While there is still more response to read 
      while ((line = httpResponseReader.readLine()) != null) { 
       // Add line to jsonString 
       jsonString += (line + "\n"); 
      } 
      // Close Response Stream 
      httpResponseStream.close(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 

     try { 
      // Create jsonObject from the jsonString and return it 
      return new JSONObject(jsonString); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
      // Return null if in error 
      return null; 
     } 
    } 
} 

它處理通信,打開一個連接並接收一個JSON字符串,然後將其處理成一個JSON對象。

2)在PHP服務器上,打開你的SQL數據庫的mysqli的連接,運行mysqli->查詢(),並完成類似,結果如下:

if (mysqli_num_rows($result) > 0) { 
     // looping through all results 
     $response["apps"] = array(); 

     while ($row = mysqli_fetch_array($result)) { 

      $apps = array(); 

      $apps["name"] = $row["name"]; 
      $apps["package"] = $row["package"]; 
      $apps["version"] = $row["version"]; 
      $apps["dateversion"] = $row["dateversion"]; 
      $apps["sdkver"] = $row["sdkver"]; 
      $apps["pathroot"] = $row["pathroot"]; 
      $apps["rootname"] = $row["rootname"]; 
      $apps["apkmd5"] = $row["apkmd5"]; 
      $apps["extraapkmd5"] = $row["extraapkmd5"]; 
      $apps["instructionsmd5"] = $row["instructionsmd5"]; 
      $apps["assetsmd5"] = $row["assetsmd5"]; 
      $apps["root"] = $row["root"]; 
      $apps["current"] = $row["current"]; 

      // push single product into final response array 
      array_push($response["apps"], $apps); 
     } 
     // success 
     $response["success"] = 1; 

     // echoing JSON response 
     echo json_encode($response); 

這遍歷數據庫響應並將其編碼爲一個JSON字符串,該字符串被髮回到可以處理它的android應用程序。

如何創建這樣的事情在教程的所有解釋鏈接

0

這不會直接回答你的問題,但因爲你」我問過從哪裏開始,你應該通過在AsyncTask中構建Web請求來正確啓動。這將允許您在單獨的線程中發出請求,並在UI上設置數據。

AsyncTasks使用線程池和工作隊列還可以很容易地更新用戶的進度。有一些很好的例子在這裏:AsyncTask Android example

相關問題