PHP-Curl模拟HTTPS请求(代码实例)

使用PHP-Curl方式模拟HTTPS请求,测试接口传参和返回值状态

上代码!!

  1. <?php
  2. /**
  3. * 模拟post进行url请求
  4. * @param string $url
  5. * @param array $postData
  6. */
  7. function request_post($url = '', $postData = []) {
  8. if (emptyempty($url)) {
  9. return false;
  10. }
  11. if ($postData != []) {
  12. $vars = http_build_query($postData, '', '&');
  13. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
  14. }
  15. $postUrl = $url;
  16. //初始化curl //转义
  17. $ch = curl_init();
  18. //抓取指定网页
  19. curl_setopt($ch, CURLOPT_URL,$postUrl);
  20. //设置header
  21. curl_setopt($ch, CURLOPT_HEADER, 0);
  22. //要求结果为字符串且输出到屏幕上
  23. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  24. //规避SSL验证
  25. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  26. //跳过HOST验证
  27. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  28. //运行curl
  29. $data = curl_exec($ch);
  30. curl_close($ch);
  31. return $data;
  32. }
  33. /**
  34. * 测试
  35. * @param string $url
  36. */
  37. function testAction() {
  38. $url = 'https://www.sojson.com/open/api/weather/json.shtml?city=北京';
  39. $res = request_post($url);
  40. print_r($res);
  41. }
  42. testAction();

结果:

PHP-Curl模拟HTTPS请求(代码实例)