首先,你必须为应用程序开发联系(WebService的,REST服务或任何适合您的需求)的一个点。就我而言,我正在使用一个生成JSON响应的PHP脚本。
下面是一个简单的PHP脚本连接到数据库,并输出一个JSON(json_encode method)回应:
<?php
$link = mysqli_connect("localhost", "dbuser", "dbpassword", "database");
$response = array();
$pass = mysqli_query("select * from table");
while($data = mysqli_fetch_object($pass))
{
array_push($response, array(
"my_field" => $data->my_field
));
}
echo json_encode($response);
mysqli_close($link);
>
脚本将输出这样的JSON响应:
[{"my_field":1}]
当您的应用程序通过HTTP POST或GET响应请求数据时,您将使用库解析答案。由于我在PHP端使用JSON,因此我目前正在为我的项目使用GSON。
为了从Android应用程序请求JSON数据,你可以使用一个RestClass我的地方了(记不清了),但这里是代码:
public class RestClient
{
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public enum RequestMethod
{
GET,
POST
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
// -------------------------------------------------------------------------------
// Various methods.
// -------------------------------------------------------------------------------
/**
* Add a parameter to the request (pair, name/value).
* @param name Name of the parameter (ex: &name=)
* @param value Value of the parameter (ex: &name=value).
*/
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Add a header to the request (if needed).
* @param name Name of the header. (ex: Content-Type)
* @param value Value of the header. (ex: Content-Type = text/html).
*/
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Fetch the HTTP content via POST or GET.
* @param method Method to be used.
* @throws Exception Exception to be catched in case of a network problem.
*/
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Alternative method to execute the HTTP request.
* @param request The HTTP request object to be used.
* @param url HTTP url.
*/
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Private method. Convert an HTTP stream to a string stream.
* @param is InputStream to be converted.
* @return String to be used.
*/
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
然后在你的Android应用程序,你可以实例的RESTClient实现类像这样(你甚至可以添加POST或GET参数查询):
RestClient c = new RestClient("http://www.myserver.com/json.php");
c.AddParam("my_field_value", 1);
try
{
c.Execute(RequestMethod.POST);
// Here you can parse the JSON with an instance of Gson class.
Gson jsonObject = new Gson();
String jsonOutput = jsonObject.toJson(c.getResponse());
// Do whatever you need with the data.
}
catch (Exception e)
{
e.printStackTrace();
}
,瞧!您可以使用从您的Android应用程序中使用PHP脚本创建的JSON数据。别忘了将android.permission.INTERNET添加到您的AndroidManifest.xml中。否则,您的应用程序将无法与您的PHP脚本进行通信。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
祝你好运。
已关闭???为什么?至少有4人发现这个问题很容易回答,他们确实很好地回答了这个问题,并且以非常有帮助的方式回答了这个问题。 – uTubeFan 2011-12-14 00:54:00