HttpHelper.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace common\util;
  3. use common\components\AjaxException;
  4. class HttpHelper
  5. {
  6. public static $connectTimeout = 30;//30 second
  7. public static $readTimeout = 80;//80 second
  8. public static function curl($url, $httpMethod = "GET", $postFields = null, $headers = null)
  9. {
  10. $ch = curl_init();
  11. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
  12. curl_setopt($ch, CURLOPT_URL, $url);
  13. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  15. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  16. if (self::$readTimeout) {
  17. curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
  18. }
  19. if (self::$connectTimeout) {
  20. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
  21. }
  22. //https request
  23. if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
  24. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  25. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  26. }
  27. if (is_array($headers) && 0 < count($headers)) {
  28. $httpHeaders = self::getHttpHearders($headers);
  29. curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeaders);
  30. }
  31. $httpResponse = new HttpResponse();
  32. $httpResponse->setBody(curl_exec($ch));
  33. $httpResponse->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  34. if (curl_errno($ch)) {
  35. throw new AjaxException("Server unreachable: Errno: " . curl_errno($ch) . " " . curl_error($ch));
  36. }
  37. curl_close($ch);
  38. return $httpResponse;
  39. }
  40. public static function getPostHttpBody($postFildes)
  41. {
  42. $content = "";
  43. foreach ($postFildes as $apiParamKey => $apiParamValue) {
  44. $content .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
  45. }
  46. return substr($content, 0, -1);
  47. }
  48. public static function getHttpHearders($headers)
  49. {
  50. $httpHeader = array();
  51. foreach ($headers as $key => $value) {
  52. array_push($httpHeader, $key . ":" . $value);
  53. }
  54. return $httpHeader;
  55. }
  56. }