php模擬post提交請求調(diào)用接口示例解析
php模擬post提交請求,調(diào)用接口
/** * 模擬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);//抓取指定網(wǎng)頁 curl_setopt($ch, CURLOPT_HEADER, 0);//設置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結(jié)果為字符串且輸出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $data = curl_exec($ch);//運行curl curl_close($ch); return $data; }
這是方法,
下面是具體的調(diào)用案例。
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); }
這樣就提交請求,并且獲取請求結(jié)果了。一般返回的結(jié)果是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);//抓取指定網(wǎng)頁 curl_setopt($ch, CURLOPT_HEADER, 0);//設置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結(jié)果為字符串且輸出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $data = curl_exec($ch);//運行curl curl_close($ch); return $data; }
將拼接也封裝了起來,這樣調(diào)用的時候就更簡潔了。
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提交請求調(diào)用接口示例解析的文章就介紹到這了,更多相關php模擬post提交請求調(diào)用接口內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. 利用CSS3新特性創(chuàng)建透明邊框三角2. html清除浮動的6種方法示例3. CSS代碼檢查工具stylelint的使用方法詳解4. Vue3使用JSX的方法實例(筆記自用)5. vue實現(xiàn)將自己網(wǎng)站(h5鏈接)分享到微信中形成小卡片的超詳細教程6. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)7. 詳解CSS偽元素的妙用單標簽之美8. 使用css實現(xiàn)全兼容tooltip提示框9. JavaScript數(shù)據(jù)類型對函數(shù)式編程的影響示例解析10. 不要在HTML中濫用div
