【问题标题】:How can I fetch data from a web server in an android application? [closed]如何从 Android 应用程序中的 Web 服务器获取数据? [关闭]
【发布时间】:2013-05-14 14:05:54
【问题描述】:

我想在 android 应用程序中从网络服务器检索数据,但不知道从哪里开始。我应该使用网络服务吗?

【问题讨论】:

  • 这是一个非常笼统的问题,但我已经发布了一个答案,其中包括三个教程的链接,涵盖了从头到尾的整个过程
  • 嗯,是关于用确切的措辞提出问题。对我来说似乎既清晰又有用!
  • “Charles, Bill the Lizard 认为这不是一个真正的问题”这个网站变得越来越荒谬..

标签: android


【解决方案1】:

我会推荐这些教程:

Connect android with PHP and MySqlJSON in androidPHP and MySQLi

我使用了这些教程并设法轻松完成了您想要做的工作。

在它们之间,它们描述了如何在每个阶段尝试执行的每个步骤、android 应用程序、数据库和 Web 服务器端,并包含额外信息,说明您可以如何处理和使用收到的信息

我唯一要补充的是,Connect android with PHP and MySql 教程在 php 中使用了 mysql_,但已弃用。使用 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->query() 并对结果执行以下操作:

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 应用程序,然后该应用程序可以对其进行处理。

如何创建这样的东西在链接的教程中都有解释

【讨论】:

    【解决方案2】:

    首先,您必须在要使用的网络服务之间进行选择。
    然后找到最适合您需求的类型。
    据我所知,解析json、xml或soap的最简单方法如下(附教程链接):
    Json :Jackson frame work
    xml :Simple framework
    soap :ksoap2 framework

    【讨论】:

      【解决方案3】:

      这不会直接回答您的问题,但既然您已经询问从哪里开始,您应该通过在 AsyncTask 中构建您的 Web 请求来正确开始。这将允许您在单独的线程中发出请求,并在 UI 上设置数据。

      AsyncTasks 使用线程池和工作队列还可以轻松地更新用户的进度。这里有一些很好的例子:AsyncTask Android example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 2016-07-08
        • 1970-01-01
        • 2021-07-15
        相关资源
        最近更新 更多