项目上需要php模拟提交post请求,所以这里记录下使用方法,方便后面再使用
01. /**
02. * 模拟post进行url请求03. * @param string $url04. * @param string $param05. */06. function request_post($url = '', $param = '') {07. if (empty($url) || empty($param)) {08. return false;09. }10. 11. $postUrl = $url;12. $curlPost = $param;13. $ch = curl_init();//初始化curl14. curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页15. curl_setopt($ch, CURLOPT_HEADER, 0);//设置header16. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上17. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式18. curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);19. $data = curl_exec($ch);//运行curl20. curl_close($ch);21. 22. return $data;23. }
下面是具体的调用方法:
01. function testAction(){
02. $url = 'http://mobile.jschina.com.cn/jschina/register.php';03. $post_data['appid'] = '10';04. $post_data['appkey'] = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';05. $post_data['member_name'] = 'zsjs123';06. $post_data['password'] = '123456';07. $post_data['email'] = 'zsjs123@126.com';08. $o = "";09. foreach ( $post_data as $k => $v ) 10. { 11. $o.= "$k=" . urlencode( $v ). "&" ;12. }13. $post_data = substr($o,0,-1);14. $res = $this->request_post($url, $post_data); 15. print_r($res);16. }
这样就提交请求,并且获取请求结果了。一般返回的结果是json格式的。
这里的post是拼接出来的。
也可以改造成下面的方式。
01./**
02. * 模拟post进行url请求03. * @param string $url04. * @param array $post_data05. */06. function request_post($url = '', $post_data = array()) {07. if (empty($url) || empty($post_data)) {08. return false;09. }10. 11. $o = "";12. foreach ( $post_data as $k => $v ) 13. { 14. $o.= "$k=" . urlencode( $v ). "&" ;15. }16. $post_data = substr($o,0,-1);17. $postUrl = $url;18. $curlPost = $post_data;19. $ch = curl_init();//初始化curl20. curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页21. curl_setopt($ch, CURLOPT_HEADER, 0);//设置header22. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上23. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式24. curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);25. $data = curl_exec($ch);//运行curl26. curl_close($ch);27. 28. return $data;29. }
将拼接也封装了起来,这样调用的时候就更简洁了。
01.function testAction(){
02. $url = 'http://mobile.jschina.com.cn/jschina/register.php';03. $post_data['appid'] = '10';04. $post_data['appkey'] = 'cmbohpffXVR03nIpkkQXaAA1Vf5nO4nQ';05. $post_data['member_name'] = 'zsjs124';06. $post_data['password'] = '123456';07. $post_data['email'] = 'zsjs124@126.com';08. //$post_data = array();09. $res = $this->request_post($url, $post_data); 10. print_r($res);11. }
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://sulao.cn/post/302
评论列表