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

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

概述前言由于学校科技立项的项目需要实现AndroidApp端与PHPWeb端的简单数据交互的实现,当前场景是Web端使用的是MySql数据库,Apache服务器和PHP语言编写的。数据交互的简单理解就是Android能向服务端进行数据获取,同时

前言

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

实现流程

流程说明

AndorID Server端对MysqL数据库进行简单的查询 *** 作,并将查询数据结果转换为Json格式提供给AndorID利用OKhttp读取再解析Json展示到APP上;同时AndorID端利用OKhttp提交给AndorID Server端,由Server端对MysqL数据库对提交数据的添加。 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方面是另外一个同学主要负责,期间也求助过我实习时结交的朋友帮助。感谢所有付出与帮助的人。希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android App端与PHP Web端的简单数据交互实现示例全部内容,希望文章能够帮你解决Android App端与PHP Web端的简单数据交互实现示例所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1144013.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存