您好,登錄后才能下訂單哦!
小編給大家分享一下Android App端與PHP Web端的簡(jiǎn)單數(shù)據(jù)交互的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
實(shí)現(xiàn)流程
流程說(shuō)明
Andorid Server端對(duì)MySql數(shù)據(jù)庫(kù)進(jìn)行簡(jiǎn)單的查詢操作,并將查詢數(shù)據(jù)結(jié)果轉(zhuǎn)換為Json格式提供給Andorid利用OKhttp讀取再解析Json展示到APP上;同時(shí)Andorid端利用OKhttp提交給Andorid Server端,由Server端對(duì)MySql數(shù)據(jù)庫(kù)對(duì)提交數(shù)據(jù)的添加。
Apache Server端通過(guò)解析PHP源代碼,對(duì)MySql數(shù)據(jù)庫(kù)的增刪查改顯示在WebSite。
具體實(shí)現(xiàn)
Andorid Server
獲取數(shù)據(jù)
get_all_found_items.php
<?php header('Content-Type:text/html;charset=utf-8');/*設(shè)置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代碼可知通過(guò)require_once()函數(shù)包含db_connect.php文件,執(zhí)行數(shù)據(jù)庫(kù)配置文件。定義數(shù)組$response接收查詢的數(shù)據(jù)結(jié)果,通過(guò)判斷不同的情況賦值$response[“success”],并返回到Web頁(yè)面顯示
PHP文件執(zhí)行結(jié)果
JSON
{ "items": [ { "what": "手表", "when": "2017-10-21 00:00:00", "where": "北區(qū)宿舍樓#504", "detail": "白色的手表,XX品牌", "posttime": "2017-10-21 13:03:09", "contact": "138123456" }, { "what": "手機(jī)", "when": "2017-10-04 00:00:00", "where": "北區(qū)商店#111", "detail": "iphone6s,土豪金", "posttime": "2017-10-21 13:03:46", "contact": "137123456" }, { "what": "電腦", "when": "2017-10-21 14:39:54", "where": "圖書(shū)館#203", "detail": "聯(lián)想品牌筆記本", "posttime": "2017-10-21 17:08:14", "contact": "5670001" }, { "what": "細(xì)說(shuō)PHP", "when": "2017-09-21 13:03:46", "where": "南館#403", "detail": "黑色封面,第二版《細(xì)說(shuō)PHP》", "posttime": "2017-10-21 17:36:53", "contact": "63513641" } ], "success": 1 }
提交數(shù)據(jù)
create_found_items.php
<?php header('Content-Type:text/html;charset=utf-8');/*設(shè)置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請(qǐng)求的參數(shù)是否都存在,把獲取的GET請(qǐng)求參數(shù)作為數(shù)據(jù)INSERT TO MySQL數(shù)據(jù)庫(kù)。判斷INSERT執(zhí)行過(guò)程賦值$response[“success”]對(duì)應(yīng)相應(yīng)的$response[“message”],顯示在Web頁(yè)面。
執(zhí)行結(jié)果
Andorid
獲取數(shù)據(jù)
核心代碼 queryLosts()函數(shù)
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 = "地點(diǎn):" + (where == null?"":where) +" "+"時(shí)間:" + (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網(wǎng)絡(luò)框架OKhttp,OKhttp一個(gè)處理網(wǎng)絡(luò)請(qǐng)求的開(kāi)源項(xiàng)目,是安卓端最火熱的輕量級(jí)框架.請(qǐng)求接口url地址,獲取Json數(shù)據(jù)利用JSONObject對(duì)Json數(shù)據(jù)進(jìn)行解析。
提交數(shù)據(jù)
核心代碼 addLost()函數(shù)
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方式提交參數(shù),try-catch獲取異常,通過(guò)返回值給出一定的提交結(jié)果提示。
代碼測(cè)試
數(shù)據(jù)同步
Web端
Andorid端
數(shù)據(jù)提交
提交結(jié)果
以上是“Android App端與PHP Web端的簡(jiǎn)單數(shù)據(jù)交互的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。