android客户端和php服务简单交互

来源:互联网 发布:go软件下载 编辑:程序博客网 时间:2024/05/16 09:14

android客户端和php+mysql+apache搭建之间的简单交互,实现log信息存储。

实现原理就是android客户端发送请求,传给服务器log信息,服务器收到这些,连接数据库进行存储,并将存储后的状态返回给客户端。

服务器端:

先在mysql里面建一个testlog的数据库,里面有一个log_info表,记录了LogCategory,System,Executor,Action等信息。

在php的虚拟目录下新建一个php项目testlog,创建conn.php和log_deal.php文件。


<?phpinclude_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服务器端存储的功能已经完成了。


0 0
原创粉丝点击