本文由 千趣源码 – qianqu 发布,转载请注明出处,如有问题请联系我们!利用php写模拟post提交请求的调用接口方法
/** * 仿真模拟post开展URL要求 * @param string $url * @param string $param */ function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $ch = curl_init();//复位curl curl_setopt($ch, CURLOPT_URL,$postUrl);//爬取特定网页页面 curl_setopt($ch, CURLOPT_HEADER, 0);//设定header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//规定結果为字符串数组且輸出到显示屏上 curl_setopt($ch, CURLOPT_POST, 1);//post递交方法 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $data = curl_exec($ch);//运作curl curl_close($ch); return $data; }
它是方式,
下边是实际的启用实例。
function testAction(){
$url = 'http://mobile.jschina.com.cn/jschina/register.php';
$post_data['APPid'] = '10';
$post_data['appkey'] = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';
$post_data['member_name'] = 'zsjs123';
$post_data['password'] = '123456';
$post_data['email'] = 'zsjs123@126.com';
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$res = $this->request_post($url, $post_data);
print_r($res);
}那样就递交要求,而且获得要求結果了。一般回到的結果是json文件格式的。
这儿的post是拼凑出去的。
还可以更新改造成下边的方法。
/**
* 仿真模拟post开展url要求
* @param string $url
* @param array $post_data
*/
function request_post($url = '', $post_data = array()) {
if (empty($url) || empty($post_data)) {
return false;
}
$o = "";
foreach ( $post_data as $k => $v )
{
$o.= "$k=" . urlencode( $v ). "&" ;
}
$post_data = substr($o,0,-1);
$postUrl = $url;
$curlPost = $post_data;
$ch = curl_init();//复位curl
curl_setopt($ch, CURLOPT_URL,$postUrl);//爬取特定网页页面
curl_setopt($ch, CURLOPT_HEADER, 0);//设定header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//规定結果为字符串数组且輸出到显示屏上
curl_setopt($ch, CURLOPT_POST, 1);//post递交方法
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch);//运作curl
curl_close($ch);
return $data;
}将拼凑也封裝了起來,那样启用的情况下就更简约了。
function testAction(){
$url = 'http://mobile.jschina.com.cn/jschina/register.php';
$post_data['appid'] = '10';
$post_data['appkey'] = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';
$post_data['member_name'] = 'zsjs124';
$post_data['password'] = '123456';
$post_data['email'] = 'zsjs124@126.com';
//$post_data = array();
$res = $this->request_post($url, $post_data);
print_r($res);
}到此这篇有关php仿真模拟post递交要求启用插口实例分析的文章内容就详细介绍到这了







