我怎样才能获取在Android应用程序从Web服务器上的数据? [英] How can I fetch data from a web server in an android application?

查看:110
本文介绍了我怎样才能获取在Android应用程序从Web服务器上的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找回在Android应用程序从Web服务器上的数据,并且不知道从哪里开始。我应该使用Web服务?

I want to retrieve data from a web server in an android application, and don't know where to begin. Should I use web services?

推荐答案

我会推荐这些教程:

连接机器人与PHP和MySQL ,< A HREF =htt​​p://www.vogella.com/articles/AndroidJSON/article.html#json_android> JSON在Android的和的 PHP与库MySQLi

我用这些教程,并设法得到你正在尝试做的工作没有太大的困难是什么。

I used these tutorials and managed to get what you are trying to do working without too much difficulty.

他们之间descibe怎么办你attemping什么在每个阶段,android的应用程序,数据库和Web服务器端,并有包括什么,你就可以做的处理和使用所接收的信息的额外信息的每一步

Between them they descibe each step in how to do what you are attemping at each stage, the android application, the database and the web server side and has extra information included for what you can then do to process and use the received information

我唯一要补充的是,连接用的android PHP和MySQL教程使用mysql_在PHP中是pcated德$ P $。最好使用库MySQLi这就是为什么我列入第三连接。

The only thing I would add is that the Connect android with PHP and MySql tutorial makes use of mysql_ in php which is deprecated. Much better to use MySqli which is why I included the third link.

您想要做什么的基本轮廓是这样的:

The basic outline of what you want to do is this:

1)在Android应用程序中使用的一类像这样提出请求到服务器PHP脚本:

1) in the android app make a request to a server php script using a class like this:

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对象。

Which handles communication, opens a connection and receives a json string which it then processes into a JSON object.

2)在PHP服务器上,打开你的SQL数据库的mysqli的连接,运行mysqli->查询(),并完成类似,结果如下:

2) in the php server, open an mysqli connection to your SQL database, run an mysqli->query() and do something like the following with the result:

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);

这遍历数据库的响应和连接codeS成被送回了Android应用程序,然后可以处理它一个JSON字符串。

This iterates through the database response and encodes it into a JSON string which is sent back to the android app which can then process it.

如何创建这样的事情是联系在一起的教程都解释

How to create something like this is all explained in the tutorials linked

这篇关于我怎样才能获取在Android应用程序从Web服务器上的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆