HttpUtils.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace app\common\library;
  3. use think\facade\Http;
  4. /**
  5. * 国密加密
  6. */
  7. class HttpUtils
  8. {
  9. /**
  10. * 发起POST请求
  11. * @param string $url 请求的URL地址
  12. * @param array $data 请求的POST数据
  13. * @param array $header 请求的头部信息
  14. * @return mixed
  15. */
  16. public static function post($url, $data = [], $header = [])
  17. {
  18. // 初始化cURL会话
  19. $ch = curl_init();
  20. // 将数据转换为JSON格式
  21. if (is_array($data)) {
  22. $data = json_encode($data);
  23. // 添加JSON头部
  24. if (!in_array('Content-Type: application/json', $header)) {
  25. $header[] = 'Content-Type: application/json';
  26. }
  27. }
  28. // halt($header);
  29. // 设置cURL选项
  30. curl_setopt($ch, CURLOPT_URL, $url);
  31. curl_setopt($ch, CURLOPT_POST, true);
  32. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  33. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  34. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  35. // 执行cURL请求
  36. $response = curl_exec($ch);
  37. // 关闭cURL会话
  38. curl_close($ch);
  39. // halt(curl_error($ch));
  40. // 返回响应内容
  41. return $response;
  42. }
  43. }