国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

php模擬post提交請求調用接口示例解析

瀏覽:94日期:2022-09-09 13:15:52

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提交請求調用接口示例解析的文章就介紹到這了,更多相關php模擬post提交請求調用接口內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: PHP
相關文章:
主站蜘蛛池模板: 海南省| 巢湖市| 信阳市| 苍溪县| 南漳县| 东海县| 威远县| 尚义县| 通化县| 青州市| 庄浪县| 禄劝| 广州市| 家居| 彭山县| 万州区| 秦皇岛市| 吴旗县| 镇巴县| 东辽县| 扬中市| 平安县| 浦城县| 陆川县| 澄迈县| 汝州市| 邵阳县| 辛集市| 普兰店市| 营口市| 漾濞| 鹰潭市| 五大连池市| 涟水县| 西畴县| 宁蒗| 鹿泉市| 贡觉县| 屯门区| 晋城| 翁牛特旗|