一聚教程网:一个值得你收藏的教程网站

热门教程

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

时间:2022-06-24 16:47:40 编辑:袖梨 来源:一聚教程网

例子

 代码如下 复制代码

$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.111com.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中内容

热门栏目