当前位置: 移动技术网 > IT编程>移动开发>Android > Android App端与PHP Web端的简单数据交互实现示例

Android App端与PHP Web端的简单数据交互实现示例

2019年07月24日  | 移动技术网IT编程  | 我要评论

sc2608,空调论坛,woog是什么牌子

前言

由于学校科技立项的项目需要实现android app端与php web端的简单数据交互的实现,当前场景是web端使用的是mysql数据库,apache服务器和php语言编写的。数据交互的简单理解就是android能向服务端进行数据获取,同时也能进行数据提交。

实现流程

流程说明

  1. andorid server端对mysql数据库进行简单的查询操作,并将查询数据结果转换为json格式提供给andorid利用okhttp读取再解析json展示到app上;同时andorid端利用okhttp提交给andorid server端,由server端对mysql数据库对提交数据的添加。
  2. apache server端通过解析php源代码,对mysql数据库的增删查改显示在website。

具体实现

andorid server

获取数据

get_all_found_items.php

<?php 
header('content-type:text/html;charset=utf-8');/*设置php编码为utf-8*/
/* 
 * following code will list all the items 
 */ 
  
// array for json response 
$response = array(); 
  
// include db connect class 
require_once __dir__ . '/db_connect.php'; 
  
// connecting to db 
$db = new db_connect(); 
  
// get all items from items table 
$result = mysql_query("select *from items where type='1'") or die(mysql_error()); 
// check for empty result 
if (mysql_num_rows($result) > 0) { 
  // looping through all results 
  // items node 
  $response["items"] = array(); 
  
  while ($row = mysql_fetch_array($result)) { 
    // temp user array 
    $items = array(); 
    $items["what"] = $row["what"]; 
    $items["when"] = $row["when"]; 
    $items["where"] = $row["where"]; 
    $items["detail"] = $row["detail"];
    $items["posttime"] = $row["posttime"];  
 $resultcontcat = mysql_query("select *from guests") or die(mysql_error()); 
 while ($row1 = mysql_fetch_array($resultcontcat)) { 
  if ($row1["id"] == $row["gid"]){
  $items["contact"] = $row1["contact"];
  }
  }
    // push single items into final response array 
    array_push($response["items"], $items); 
  } 
  // success 
  $response["success"] = 1; 
  
  // echoing json response 
  echo json_encode($response,json_unescaped_unicode); 
} else { 
  // no items found 
  $response["success"] = 0; 
  $response["message"] = "no items found"; 
  
  // echo json 
  echo json_encode($response,json_unescaped_unicode); 
} 
?>

如以上php代码可知通过require_once()函数包含db_connect.php文件,执行数据库配置文件。定义数组$response接收查询的数据结果,通过判断不同的情况赋值$response[“success”],并返回到web页面显示

php文件执行结果

json

 {
  "items": [
    {
      "what": "手表",
      "when": "2017-10-21 00:00:00",
      "where": "北区宿舍楼#504",
      "detail": "白色的手表,xx品牌",
      "posttime": "2017-10-21 13:03:09",
      "contact": "138123456"
    },
    {
      "what": "手机",
      "when": "2017-10-04 00:00:00",
      "where": "北区商店#111",
      "detail": "iphone6s,土豪金",
      "posttime": "2017-10-21 13:03:46",
      "contact": "137123456"
    },
    {
      "what": "电脑",
      "when": "2017-10-21 14:39:54",
      "where": "图书馆#203",
      "detail": "联想品牌笔记本",
      "posttime": "2017-10-21 17:08:14",
      "contact": "5670001"
    },
    {
      "what": "细说php",
      "when": "2017-09-21 13:03:46",
      "where": "南馆#403",
      "detail": "黑色封面,第二版《细说php》",
      "posttime": "2017-10-21 17:36:53",
      "contact": "63513641"
    }
  ],
  "success": 1
}

提交数据

create_found_items.php

<?php 
header('content-type:text/html;charset=utf-8');/*设置php编码为utf-8*/  
/* 
 * following code will create a new product row 
 * all product details are read from http get request 
 */ 
  
// array for json response 
$response = array(); 
  
// check for required fields 
if (isset($_get['what']) && isset($_get['when']) && isset($_get['where']) && isset($_get['detail'])&& isset($_get['contact'])) { 
  
  $what = $_get['what']; 
  $when = $_get['when']; 
  $where = $_get['where']; 
  $detail = $_get['detail']; 
  $contact = $_get['contact']; 
 
  // include db connect class 
  require_once __dir__ . '/db_connect.php'; 
  
  // connecting to db 
  $db = new db_connect(); 
  
  // mysql inserting a new row 
 $result2 = mysql_query("insert into guests(contact) values('$contact')"); 
 $gidresult = mysql_query("select id from `guests` where contact='$contact'"); 
 while ($row = mysql_fetch_array($gidresult)) { 
  $gid=$row['id'];
 }
  $result1 = mysql_query("insert into items(`what`, `when`, `where`, `type` ,`gid`, `detail`) values('$what', '$when', '$where', '1', '$gid', '$detail')");  
  
  // check if row inserted or not 
  if ($result1 && $result2) { 
    // successfully inserted into database 
    $response["success"] = 1; 
    $response["message"] = "items successfully created."; 
  
    // echoing json response 
  echo json_encode($response,json_unescaped_unicode);  
  } else { 
    // failed to insert row 
    $response["success"] = 0; 
    $response["message"] = "oops! an error occurred."; 
  
    // echoing json response 
  echo json_encode($response,json_unescaped_unicode);  
  } 
} else { 
  // required field is missing 
  $response["success"] = 0; 
  $response["message"] = "required field(s) is missing"; 
  
  // echoing json response 
  echo json_encode($response,json_unescaped_unicode);  
} 
?>

判断get请求的参数是否都存在,把获取的get请求参数作为数据insert to mysql数据库。判断insert执行过程赋值$response[“success”]对应相应的$response[“message”],显示在web页面。

执行结果

andorid

获取数据

核心代码 querylosts()函数

private void querylosts() {
 losts.clear();
 new thread(new runnable() {
 
 @override
 public void run() {
  // todo auto-generated method stub
  
     okhttpclient okhttpclient = new okhttpclient();
     string url = "http://website/androidapi/get_all_lost_items.php";
     request request = new request.builder()
         .url(url)
         .build();
     call call = okhttpclient.newcall(request);
     try {
       response response = call.execute();
       string res = response.body().string();
       if (res != null && !res.trim().equals("")){
         jsonobject jsonobject = new jsonobject(res);
         if (jsonobject.getint("success") == 1){
           jsonarray jsonarray = jsonobject.getjsonarray("items");
           for (int i = jsonarray.length() - 1;i >= 0;i--){
             jsonobject item = jsonarray.getjsonobject(i);
             string what = null;
             try {
               what = item.getstring("what");
             }catch (exception e){
             }
             string when = null;
             try{
               when = item.getstring("when");
             }catch (exception e){
             }
             string where = null;
             try{
               where = item.getstring("where");
             }catch (exception e){
             }
             string detail = null;
             try {
               detail = item.getstring("detail");
             }catch (exception e){
             }
             string contact = null;
             try {
               contact = item.getstring("contact");
             }catch (exception e){
             }
             lost lost = new lost();
             lost.settitle(what);
             string des = "地点:" + (where == null?"":where) +"   "+"时间:" + (when == null?"":when)+"\r" + "   "+"描述:" + (detail == null?"":detail);
             lost.setdescribe(des);
             lost.setphone(contact == null?"":contact);
             losts.add(lost);
           }
         }
       }
     } catch (exception e) {
       e.printstacktrace();
       showerrorview(0);
     }
     if (losts == null || losts.size() == 0) {
     handler.sendemptymessage(1);
       return;
     }
     if (losts.size() > 0){
      handler.sendemptymessage(2);
     }
 }
 }).start();

利用android网络框架okhttp,okhttp一个处理网络请求的开源项目,是安卓端最火热的轻量级框架.请求接口url地址,获取json数据利用jsonobject对json数据进行解析。

提交数据

核心代码 addlost()函数

public handler handler = new handler(){
 public void handlemessage(android.os.message msg) {
 switch(msg.what){
  case 1:
  toast.maketext(this,"提交成功",toast.length_long).show();
  break;
  case 2:
  toast.maketext(this,"提交失败",toast.length_long).show();
  break;
 }
 }
};
private void addlost(){
 okhttpclient okhttpclient = new okhttpclient();
 string url ="http://website/androidapi/create_lost_items.php?what="+title+"&when="+time+"&where="+place+"&detail="+describe+"&contact="+photo+"";
 request request = new request.builder()
  .url(url)
  .build();
 
 try{
 response response = okhttpclient.newcall(request).execute();
 res = response.body().string();
 handler.sendemptymessage(1);
 }catch (exception e)
 {
 e.printstacktrace();
 handler.sendemptymessage(2);
 }
}

同样利用okhttp,get方式提交参数,try-catch获取异常,通过返回值给出一定的提交结果提示。

代码测试

数据同步

web端

andorid端

数据提交

提交结果

结语

以上过程基本实现,项目基本上可以交差了。这个项目php部分主要是由自己在弄,也是边学边做。android方面是另外一个同学主要负责,期间也求助过我实习时结交的朋友帮助。感谢所有付出与帮助的人。希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网