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?
我想从Android应用程序中的Web服务器检索数据,并且不知道从哪里开始。我应该使用网络服务吗?
3 个解决方案
#1
24
I would recommend these tutorials:
我会推荐这些教程:
Connect android with PHP and MySql, JSON in android and PHP and MySQLi
在Android和PHP和MySQLi中连接Android与PHP和MySql,JSON
I used these tutorials and managed to get what you are trying to do working without too much difficulty.
我使用了这些教程并设法在没有太多困难的情况下获得您正在尝试的工作。
Between them they describe each step in how to do what you are attempting 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应用程序,数据库和Web服务器端执行您所尝试的操作的每一步,并包含额外信息,以便您可以执行哪些操作来处理和使用收到的信息
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.
我唯一要补充的是Connect PHP with PHP和MySql教程使用了不推荐使用的php中的mysql_。使用MySqli要好得多,这就是我加入第三个链接的原因。
The basic outline of what you want to do is this:
你想要做的基本概述是这样的:
1) in the android app make a request to a server php script using a class like this:
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;
}
}
}
Which handles communication, opens a connection and receives a JSON string which it then processes into a JSON object.
它处理通信,打开连接并接收JSON字符串,然后将其处理为JSON对象。
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:
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);
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.
这将迭代数据库响应并将其编码为JSON字符串,然后发送回Android应用程序,然后可以处理它。
How to create something like this is all explained in the tutorials linked
如何创建这样的东西都在链接的教程中解释
#2
1
First you have to choose between the webservice you are going to use.
Then find which type will best suite your needs.
According to me , the easiest way to parse json, xml or soap are s follows(with tutorial link):
Json :Jackson frame work
xml :Simple framework
soap :ksoap2 framework
首先,您必须在要使用的Web服务之间进行选择。然后找出最符合您需求的类型。根据我的说法,解析json,xml或soap的最简单方法是跟随(使用教程链接):Json:Jackson框架工作xml:简单框架soap:ksoap2框架
#3
0
This won't directly answer your question but since you've asked where to start you should start correctly by building your web requests in an AsyncTask. This will allow you to make your requests in a seperate thread, and set the data on the UI.
这不会直接回答您的问题,但由于您已经问过从哪里开始,您应该通过在AsyncTask中构建Web请求来正确启动。这将允许您在单独的线程中发出请求,并在UI上设置数据。
AsyncTasks use a thread pool and work queue also make it easy to update the user on the progress. There are some good examples here: AsyncTask Android example
AsyncTasks使用线程池和工作队列也可以轻松更新用户的进度。这里有一些很好的例子:AsyncTask Android示例
#1
24
I would recommend these tutorials:
我会推荐这些教程:
Connect android with PHP and MySql, JSON in android and PHP and MySQLi
在Android和PHP和MySQLi中连接Android与PHP和MySql,JSON
I used these tutorials and managed to get what you are trying to do working without too much difficulty.
我使用了这些教程并设法在没有太多困难的情况下获得您正在尝试的工作。
Between them they describe each step in how to do what you are attempting 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应用程序,数据库和Web服务器端执行您所尝试的操作的每一步,并包含额外信息,以便您可以执行哪些操作来处理和使用收到的信息
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.
我唯一要补充的是Connect PHP with PHP和MySql教程使用了不推荐使用的php中的mysql_。使用MySqli要好得多,这就是我加入第三个链接的原因。
The basic outline of what you want to do is this:
你想要做的基本概述是这样的:
1) in the android app make a request to a server php script using a class like this:
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;
}
}
}
Which handles communication, opens a connection and receives a JSON string which it then processes into a JSON object.
它处理通信,打开连接并接收JSON字符串,然后将其处理为JSON对象。
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:
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);
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.
这将迭代数据库响应并将其编码为JSON字符串,然后发送回Android应用程序,然后可以处理它。
How to create something like this is all explained in the tutorials linked
如何创建这样的东西都在链接的教程中解释
#2
1
First you have to choose between the webservice you are going to use.
Then find which type will best suite your needs.
According to me , the easiest way to parse json, xml or soap are s follows(with tutorial link):
Json :Jackson frame work
xml :Simple framework
soap :ksoap2 framework
首先,您必须在要使用的Web服务之间进行选择。然后找出最符合您需求的类型。根据我的说法,解析json,xml或soap的最简单方法是跟随(使用教程链接):Json:Jackson框架工作xml:简单框架soap:ksoap2框架
#3
0
This won't directly answer your question but since you've asked where to start you should start correctly by building your web requests in an AsyncTask. This will allow you to make your requests in a seperate thread, and set the data on the UI.
这不会直接回答您的问题,但由于您已经问过从哪里开始,您应该通过在AsyncTask中构建Web请求来正确启动。这将允许您在单独的线程中发出请求,并在UI上设置数据。
AsyncTasks use a thread pool and work queue also make it easy to update the user on the progress. There are some good examples here: AsyncTask Android example
AsyncTasks使用线程池和工作队列也可以轻松更新用户的进度。这里有一些很好的例子:AsyncTask Android示例