android用戶端和php服務簡單互動
android用戶端和php+mysql+apache搭建之間的簡單互動,實現log資訊儲存。
實現原理就是android用戶端發送請求,傳給伺服器log資訊,伺服器收到這些,串連資料庫進行儲存,並將儲存後的狀態返回給用戶端。
伺服器端:
先在mysql裡面建一個testlog的資料庫,裡面有一個log_info表,記錄了LogCategory,System,Executor,Action等資訊。
在php的虛擬目錄下建立一個php項目testlog,建立conn.php和log_deal.php檔案。
';$System = $_POST['System'];$LogCategory = $_POST['LogCategory'];$Executor = $_POST['Executor'];$Action = $_POST['Action'];$sqlstr = "insert into log_info(System,LogCategory,Executor,Action,CreateTime) values('".$System."','".$LogCategory."','".$Executor."','".$Action."','".date('Y-m-d H:m:s')."')"; if (mysql_query($sqlstr)){ echo "succeed"; } else { die(mysql_error()); echo "error"; }?>伺服器搭建完成。
android用戶端:
布局隨意寫一下就OK了
下面是主要代碼:
class SendlogHandler implements Runnable{ @Override public void run() { try { String url = "http://localhost/testlog/log_deal.php"; String result = null; boolean isSendSucceed = false; HttpPost httpRequest = new HttpPost(url); List params = new ArrayList(); params.add(new BasicNameValuePair("System", "系統名稱")); params.add(new BasicNameValuePair("LogCategory", "LOG等級")); params.add(new BasicNameValuePair("Executor", "操作人")); params.add(new BasicNameValuePair("Action", "發生了什麼事")); httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); int stateCode = httpResponse.getStatusLine().getStatusCode(); if (stateCode == 200){ HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); } if (result.equals("succeed")){ isSendSucceed = true; } Message msg = new Message(); msg.what = 2; msg.obj = isSendSucceed; handler.sendMessage(msg); } catch (Exception e){ e.printStackTrace(); } } }好了,簡單的用戶端post資料到php伺服器端儲存的功能已經完成了。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。