android客戶端和php+mysql+apache搭建之間的簡單交互,實現log信息存儲。
實現原理就是android客戶端發送請求,傳給服務器log信息,服務器收到這些,連接數據庫進行存儲,並將存儲後的狀態返回給客戶端。
服務器端:
先在mysql裏面建一個testlog的數據庫,裏面有一個log_info表,記錄了LogCategory,System,Executor,Action等信息。
在php的虛擬目錄下新建一個php項目testlog,創建conn.php和log_deal.php文件。
<?php
include_once('conn.php');
//echo '$_POST接收:</br>';
$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服務器端存儲的功能已經完成了。