Home > php教程 > PHP源码 > PHP 使用 POST 方式向https发送数据请求

PHP 使用 POST 方式向https发送数据请求

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-08 17:19:36
Original
1337 people have browsed it

要使用php发送post请求我们用到curl即可实现了,这个是最简单并且性能最好的一个请求方式,下面来看这个PHP 使用 POST 方式向https发送数据请求的例子。

<script>ec(2);</script>

例子

 代码如下 复制代码

$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 '

';<br>
print_r($rs);<br>
echo '
Copy after login
';


例子

方法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中内容

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template