一、接口代码
1.1 创建数据库的SQL语句
DROP TABLE IF EXISTS `test`.`domain_statistics_result`;
CREATE TABLE `test`.`domain_statistics_result` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`domain` varchar(256) DEFAULT NULL,
`statistics_ts` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`statistics_count` int(11) NOT NULL DEFAULT '0',
`update_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
, PRIMARY KEY (`id`));
1.2 代码
if (!empty($_GET))
{
extract($_GET);
}
if (!empty($_POST))
{
extract($_POST);
}
$conn = mysql_connect('localhost', 'root', 'love') or die("cann't connect to mysql." . mysql_error());
mysql_select_db('test', $conn) or die("cann't connect to db test" . mysql_error());
$content = file_get_contents("php://input");
//print "php post response: " . $content . "\n";
//{"ts":"2016-01-12-16:50:21", "data":{"www.baidu.com":100, "www.360.cn":200, "www.alipay.com":300}}
$list = explode("\n", $content);
foreach($list as $line)
{
if (empty($line))
{
continue;
}
$line_json = json_decode($line, true);
$statistics_ts = $line_json['ts'];
$data_arr = $line_json['data'];
foreach($data_arr as $domain=>$statistics_count)
{
$sql = "insert into domain_statistics_result(domain, statistics_ts, statistics_count) values(\"$domain\", \"$statistics_ts\", $statistics_count)";
if (FALSE == mysql_query($sql))
{
print "error:" . mysql_error() . "\n";
}
}
//以下是别的地方的代码,与本代码毫无关系,不过可以参照其中的SQL方法的调用
//$sql = "select * from probe_result where agent_ip = $sip and pcache_ip = $dip";
//$res = mysql_query($sql);
//if (mysql_num_rows($res) == 0)
//{
// mysql_free_result($res);
// $sql = "insert into probe_result(agent_ip, pcache_ip, probe_result, probe_info) values($sip, $dip, $state, $info)";
// mysql_query($sql);
// continue;
//}
//while ($row = mysql_fetch_array($res))
//{
// if ($row["probe_result"] != $state)
// {
// $sql = "update probe_result set probe_result = $state, probe_info = $info where agent_ip = $sip and pcache_ip = $dip";
// mysql_query($sql);
// }
//}
//mysql_free_result($res);
}
mysql_close($conn);
?>
二、测试POST接口
1.2 curl测试post
curl 的 -d 是提交post的数据。
curl 192.168.175.131/upload.php -d "{\"ts\":\"2016-01-12-16:50:21\", \"data\":{\"www.baidu.com\":100, \"www.360.cn\":200, \"www.alipay.com\":300}}"