HttpHelper.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Aliyun\Core\Http;
  3. use Aliyun\Core\Exception\ClientException;
  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. if(ENABLE_HTTP_PROXY) {
  13. curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
  14. curl_setopt($ch, CURLOPT_PROXY, HTTP_PROXY_IP);
  15. curl_setopt($ch, CURLOPT_PROXYPORT, HTTP_PROXY_PORT);
  16. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  17. }
  18. curl_setopt($ch, CURLOPT_URL, $url);
  19. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  20. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  21. curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields);
  22. if (self::$readTimeout) {
  23. curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
  24. }
  25. if (self::$connectTimeout) {
  26. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
  27. }
  28. //https request
  29. if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
  30. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  31. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  32. }
  33. if (is_array($headers) && 0 < count($headers))
  34. {
  35. $httpHeaders =self::getHttpHearders($headers);
  36. curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeaders);
  37. }
  38. $httpResponse = new HttpResponse();
  39. $httpResponse->setBody(curl_exec($ch));
  40. $httpResponse->setStatus(curl_getinfo($ch, CURLINFO_HTTP_CODE));
  41. if (curl_errno($ch))
  42. {
  43. throw new ClientException("Server unreachable: Errno: " . curl_errno($ch) . " " . curl_error($ch), "SDK.ServerUnreachable");
  44. }
  45. curl_close($ch);
  46. return $httpResponse;
  47. }
  48. static function getPostHttpBody($postFildes){
  49. $content = "";
  50. foreach ($postFildes as $apiParamKey => $apiParamValue)
  51. {
  52. $content .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
  53. }
  54. return substr($content, 0, -1);
  55. }
  56. static function getHttpHearders($headers)
  57. {
  58. $httpHeader = array();
  59. foreach ($headers as $key => $value)
  60. {
  61. array_push($httpHeader, $key.":".$value);
  62. }
  63. return $httpHeader;
  64. }
  65. }