HttpClient.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace ACES\Common;
  3. use RuntimeException;
  4. use ACES\Common\Exception as Ex;
  5. use Monolog\Logger;
  6. use Monolog\Handler\StreamHandler;
  7. use Monolog\Formatter\LineFormatter;
  8. if(!defined("LOGCONSOLE")){
  9. define("LOGCONSOLE", __DIR__."/../../../tde.log");
  10. }
  11. if(!defined("LOGLEVEL")){
  12. define("LOGLEVEL", Logger::DEBUG);
  13. }
  14. final class HttpClient
  15. {
  16. public static function sendData($requestUrl, $method, $payload, $additional){
  17. // confige log
  18. $log = new Logger('httpClient');
  19. $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message%\r\n");
  20. $handle = new StreamHandler(LOGCONSOLE, LOGLEVEL);
  21. $handle->setFormatter($formatter);
  22. $log->pushHandler($handle);
  23. $response = null;
  24. $rootCause = '';
  25. $hasConn = False;
  26. for($retry=0;$retry<Constants::HTTP_RETRY_MAX && !$hasConn;$retry++){
  27. try {
  28. $ch = curl_init($requestUrl);
  29. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
  30. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, Constants::HTTP_TIMEOUT);
  31. curl_setopt($ch, CURLOPT_TIMEOUT_MS, Constants::HTTP_TIMEOUT);
  32. curl_setopt($ch, CURLOPT_RETURNTRANSFER, True); // True to return the transfer as a string of the return value
  33. curl_setopt($ch, CURLOPT_HTTPHEADER, $additional);
  34. curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  35. // curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
  36. $response = curl_exec($ch);
  37. // Get the error number for the last cURL operation, if no error occurs then return 0.
  38. if(curl_errno($ch)){
  39. $rootCause = curl_error($ch);
  40. throw new Ex\HttpConnectionException(curl_error($ch));
  41. }
  42. $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  43. if($response_code != 200){
  44. $rootCause = "Wrong http reponse code:".$response_code;
  45. throw new Ex\HttpConnectionException("Wrong http reponse code:".$response_code);
  46. }
  47. // todo: can this way keep connection alive?
  48. curl_close($ch);
  49. $hasConn = True;
  50. } catch (Ex\HttpConnectionException $e) {
  51. $log->critical("Http sendData error: " . $e->getMessage());
  52. }
  53. }
  54. if(!$hasConn){
  55. $log->critical("HTTP Client cannot establish connection:".$rootCause);
  56. throw new RuntimeException("HTTP Client cannot establish connection:".$rootCause);
  57. }
  58. return $response;
  59. }
  60. }