Request.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Services\Vendor\BaiduAi;
  3. use Ixudra\Curl\Facades\Curl;
  4. class Request
  5. {
  6. /**
  7. * @param string $url
  8. * @param array $data HTTP POST BODY
  9. * @param array $params
  10. * @param array $headers HTTP header
  11. * @return array
  12. */
  13. public function post($url, $data = array(), $params = array(), $headers = array())
  14. {
  15. $url = $this->buildUrl($url, $params);
  16. $headers = $this->buildHeaders($headers);
  17. $response = Curl::to($url)->withData($data)->withHeaders($headers)->asJsonResponse(true)->post();
  18. return $response;
  19. }
  20. /**
  21. *
  22. * @param string $url
  23. * @param array $params 参数
  24. * @return string
  25. */
  26. private function buildUrl($url, $params)
  27. {
  28. if (!empty($params)) {
  29. $str = http_build_query($params);
  30. return $url . (strpos($url, '?') === false ? '?' : '&') . $str;
  31. } else {
  32. return $url;
  33. }
  34. }
  35. /**
  36. * 构造 header
  37. * @param array $headers
  38. * @return array
  39. */
  40. private function buildHeaders($headers)
  41. {
  42. $result = array();
  43. foreach ($headers as $k => $v) {
  44. $result[] = sprintf('%s:%s', $k, $v);
  45. }
  46. return $result;
  47. }
  48. /**
  49. * @param string $url
  50. * @param array $params
  51. * @param array $headers HTTP header
  52. * @return array
  53. */
  54. public function get($url, $params = array(), $headers = array())
  55. {
  56. $url = $this->buildUrl($url, $params);
  57. $headers = $this->buildHeaders($headers);
  58. $response = Curl::to($url)->asJsonResponse(true)->get();
  59. return $response;
  60. }
  61. }