Home  >  Article  >  Backend Development  >  android客户端跟php服务简单交互

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

WBOY
WBOYOriginal
2016-06-13 12:23:411094browse

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文件。


<?php include_once(&#39;conn.php&#39;);		//echo &#39;$_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服务器端存储的功能已经完成了。


版权声明:本文为博主原创文章,未经博主允许不得转载。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn