curl发起post,header
2019-06-16 11:01
232 查看
curl发起post,header function call($postArr,$url,$headerArr) { //启动一个CURL会话 $ch = curl_init(); // 设置curl允许执行的最长秒数 curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8'); // 证书 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false) ; // 获取的信息以文件流的形式返回,而不是直接输出,需要设置,因为默认是0,即返回的数据无法通过变量来接收,而是直接输出了。 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //发送一个常规的POST请求。 curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); //要传送的所有数据 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postArr)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr); // 执行操作 $res = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($res == NULL) { curl_close($ch); return false; } else if($code != "200") { curl_close($ch); return false; } curl_close($ch); return $res; } 调用 $postArr = array( 'accid' => 'qwerty123', 'name' => 'raoxiaoya', 'mobile'=> '15919906312' ); $headers = array( 'AppKey: '.$AppKey, 'Nonce: '.$Nonce, 'CurTime: '.$CurTime, 'CheckSum: '.strtolower(SHA1($AppSecret . $Nonce . $CurTime)), 'Content-Type: application/x-www-form-urlencoded;charset=utf-8' ); call($postArr,$url,$headerArr); 小结 1、CURLOPT_RETURNTRANSFER 获取的信息以文件流的形式返回,需要设置为1,因为默认是0,即返回的数据无法通过变量来接收,而是直接输出了; 2、CURLOPT_POST 设置为1 3、CURLOPT_POSTFIELDS post的字段,可以接收字符串(&连接的)或数组。 如果是一维数组的话,可以直接传;如果是超过一维了,则会报错,因此,建议先通过 http_build_query 来转义成字符串再传。 4、http_build_query (多维)数组->(多维)关联数组->&连接的字符串->urlencode转义 示例: $data = array('foo', 'bar', 'baz', 'boom', 'milk', 'hypertext_processor'); echo http_build_query($data) . "\n"; // 0=foo&1=bar&2=baz&3=boom&4=milk&5=hypertext_processor $param = array('foo' => ['bar' => 'cow']); echo http_build_query($param) . "\n"; // foo%5Bbar%5D=cow 这是什么?我们urldecode一下得到 foo[bar]=cow 一个精简的post请求 function cutl_post($url, $postArr){ $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postArr)); $res = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($res == NULL) { curl_close($ch); return false; } else if($code != "200") { curl_close($ch); return false; } curl_close($ch); return $res; }
相关文章推荐
- 封装的curl 支持get post header
- php-curl(模拟post,设置header,接收json数据)
- PHP curl post header
- 后台发起post请求,并返回请求结果
- PHP 下 CURL 通过 POST 提交表单失败的原因及解决方法
- swift post json and header
- Java代码发起HTTP GET和POST请求(URLConnection)
- linux命令发送http的get或post请求(curl和wget两种方法)
- curl 中post 传参数给server
- PHP中使用CURL实现GET和POST请求的方法
- PHP使用curl模拟post上传及接收文件的方法
- 使用curl发起https请求
- curl 指令发起 post请求
- php 通过CURL 发送Http的post请求
- 使用Curl、socket、file_get_contents三种方法POST提交数据
- php通过CURL模拟post提交请求
- Python3模拟curl发送post请求操作示例
- php curl发起post请求(json和xml)
- php接口测试 curl实现GET/POST
- RCA:未注意Curl-library Post 1024以上字节时的HTTP/1.1特性导致 HessianPHP 传输数据失败