作者:于磊com | 来源:互联网 | 2018-07-15 20:24
要使用php发送post请求我们用到curl即可实现了,这个是最简单并且性能最好的一个请求方式,下面来看这个PHP使用POST方式向https发送数据请求的例子。
要使用php发送post请求我们用到curl即可实现了,这个是最简单并且性能最好的一个请求方式,下面来看这个PHP 使用 POST 方式向https发送数据请求的例子。
例子
代码如下 |
|
$data = '{"type":"news", "offset":50, "count":20 }';
$access_token = "0erCbg(此处省略112个字)DZrOR0PJBFLhAHAMQW";
$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$access_token;
// 发送数据
$ch = curl_init();
$timeout = 300;
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_REFERER, "http://www.111cn.net/"); // 伪装来路
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // URL为SSL时添加这行可解决页面空白
$rs = curl_exec($ch);
curl_close($ch);
// 输出
$rs = json_decode($rs);
echo ' ';
print_r($rs);
echo ' ';
|
例子
方法1感觉也很笨拙,似乎也很难满足我的需求,最后忘记在哪个英文网站上找到了下面这个方法:
代码如下 |
|
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$respOnse= @stream_get_contents($fp);
if ($respOnse=== false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
} |
试用了一下,感觉效果非常好,简洁,通用,而且返回的内容仅仅是Body中内容