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

前言

由于学校科技立项的项目需要实现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方面是另外一个同学主要负责,期间也求助过我实习时结交的朋友帮助。感谢所有付出与帮助的人。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

时间: 2024-08-06 21:09:16

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

android ASHX是什么?怎么去使用访问服务器做数据交互

问题描述 android ASHX是什么?怎么去使用访问服务器做数据交互 在android 怎么用ASHX访问服务器?求源码,谢谢.anikaka@sina.com

Android中Retrofit 2.0直接使用JSON进行数据交互

之前使用Retrofit都是将JSON串转化为POJO对象,针对不同的业务协议,定义相应的接口和参数列表.但是此种方式一般用在自己内部协议基础上,具体大的项目中,有些第三方的集成功能,一般都采用统一的方式即请求JSON和回应JSON进行数据交互,不可能每个第三方协议都会去定义与协议相应的POJO对象. HTTP肯定有GET和POST方法,先定义Retrofit Api的interface: package com.hdnetworklib.network.http; import java.ut

手机端和web端能不能同时登陆?

问题描述 手机端和web端能不能同时登陆?如果可以,消息的收发会有什么问题吗? 解决方案 同一个账号在同一时刻只能登陆一个设备.之前登陆的这个账号会被后来登陆的同一个账号踢掉.上面这句话是针对app端的.web端和app端可以共存.

web前端-如何在服务器与web端传递消息?

问题描述 如何在服务器与web端传递消息? 各路大神,你们好.我用java socket写了一个监听端口,接收到数据就会返回一个字符串.我现在想在web网页端做一个按钮,一按就向服务端请求并将返回字符串打印在屏幕上,这个应该如何实现?我试过用javascript的websocket,可是行不通.请问大家该怎么办? 请问有没有web端可以直接接收到字符串打印在网页的某个文本框里? 用现有的程序可以吗?我也可提供我的后端源码. 这是服务器端接收来自web端并返回web端的方法: static voi

jquery ajax-關於android app端 跟 web端的幻燈片功能+嵌入音樂功能

问题描述 關於android app端 跟 web端的幻燈片功能+嵌入音樂功能 想問一下 我想做一個類似 很多app第一次下載會出現的可能四到五個自己app的介紹(全屏的) 的樣式 但是我想做成是自動跑的(使用者可以選擇"暫停" 或者 "忽略") 但重點是"我可以插入音樂"=> 使用者沒法關掉音樂 除非他點擊"忽略"直接進入到app裡面 但我音樂系統會強制配合那四到五個app全屏頁面的介紹時間長度 (就是可能展示時間只有

横竖屏切换-android app启动时根据是手机端还是Pad端进行横竖屏判断,以及不同布局

问题描述 android app启动时根据是手机端还是Pad端进行横竖屏判断,以及不同布局 如何判断一个app,如果运行在平板上,就横屏展示,如果运行在手机上就竖屏展示.而且在这两个端不允许横竖屏切换.而且MainActivity得长的不一样.意思就是要有两套布局.需要建什么资源文件夹 解决方案 http://jingyan.baidu.com/article/455a9950aa8aaea16627788a.html

android如何通过httpclient将值传给web端

问题描述 android如何通过httpclient将值传给web端 现在在做一个软件就是安卓移动端可以评价 我该如何点击 满意 这个按钮之后就可以在web端的数据库中满意增加一呢 解决方案 给按钮添加onclicklistener监听器,以健值对字符串发送请求,请求的模式上网百度就有,web端写一个控制类里面写控制函数对数据库进行操作 解决方案二: 百度一下httpclient一大堆,Android-Async-Http这个第三方包也很好用

web端是否可以使用用户自己线上app的用户id和密码登陆?

问题描述 web端是否可以使用用户自己线上app的用户id和密码登陆? 解决方案 可以,但是需要修改appkey,在ndex.html里面修改

请问如何使用JSON将web端访问的Mysql数据返回给android客户端

问题描述 请各位大神稍微讲解下方法,最好有点代码参考下哈 解决方案 你需要搜一下Gson,和apache httpclient下载导入对应的jar包web端: 首先,想办法把mysql取出的数据放到一个list中: 然后,参考这个帖子http://huyizizhen.iteye.com/blog/1453621 将list转成json 最后,返回给客户端out.println(json.toString());客户端: 需要一个httpclient String jsonstr = httpc