/** * Constructor. * * @param CurlResponse $response Curl Response object. * @param LoggerInterface $logger Shared instance of a Logger. * @param string $device_id The deviceID that the message was sent to. */ public function __construct($response, $logger, $device_id) { $this->http_code = $response->http_code; $this->result = $response->get_result(); if ($response->get_network_error_number() !== 0) { $this->status = PushNotificationStatus::ERROR; $context = ['error' => $response->get_network_error_message(), 'endpoint' => $device_id]; $logger->warning('Dispatching push notification to {endpoint} failed: {error}', $context); } else { $this->set_status($device_id, $logger); } }
/** * Make an HTTP request * @param $url - request url * @param $method - HTTP method to use for the request * @param array $headers - any http headers that should be included with the request * @param string|null $data - payload to send with the request, if any * @return CurlResponse * @throws CTCTException */ private static function httpRequest($url, $method, array $headers = array(), $data = null) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_USERAGENT, "ConstantContact AppConnect PHP Library v1.1"); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); // add data to send with request if present if ($data) { curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } $response = CurlResponse::create(curl_exec($curl), curl_getinfo($curl), curl_error($curl)); curl_close($curl); // check if any errors were returned $body = json_decode($response->body, true); if (isset($body[0]) && array_key_exists('error_key', $body[0])) { $ex = new CtctException($response->body); $ex->setCurlInfo($response->info); $ex->setErrors($body); throw $ex; } return $response; }
protected function sendInternal(CurlConfig $config, $startTime = null, $retryCount = 1) { if (empty($config->url)) { throw new InvalidConfigException("You can't send a request without setting the url first."); } if ($startTime === null) { $startTime = time(); } if (!is_resource($this->handle)) { $this->handle = curl_init(); } else { curl_reset($this->handle); } if (!empty($config->cookies)) { curl_setopt($this->handle, CURLOPT_COOKIE, http_build_query($config->cookies, '', '; ', PHP_QUERY_RFC3986)); } if (!empty($config->headers)) { $headers = []; foreach ($config->headers as $name => $value) { $headers[] = "{$name}: {$value}"; } curl_setopt($this->handle, CURLOPT_HTTPHEADER, $headers); } if (!empty($config->referer)) { curl_setopt($this->handle, CURLOPT_REFERER, $config->referer); } curl_setopt_array($this->handle, [CURLOPT_ENCODING => 'gzip,deflate', CURLOPT_URL => $config->url, CURLOPT_POST => $config->method === self::METHOD_POST, CURLOPT_USERAGENT => $config->userAgent, CURLOPT_AUTOREFERER => $config->autoReferer, CURLOPT_FOLLOWLOCATION => $config->followRedirects, CURLOPT_MAXREDIRS => $config->maxRedirects, CURLOPT_CONNECTTIMEOUT => (int) $config->connectTimeout, CURLOPT_TIMEOUT => (int) $config->globalTimeout, CURLOPT_HEADER => true, CURLOPT_NOBODY => $config->headersOnly, CURLOPT_RETURNTRANSFER => true, CURLOPT_FORBID_REUSE => !$config->reuseConnection, CURLOPT_MAX_RECV_SPEED_LARGE => $config->maxReceiveSpeed, CURLOPT_MAX_SEND_SPEED_LARGE => $config->maxSendSpeed, CURLOPT_LOW_SPEED_LIMIT => $config->lowSpeedLimit, CURLOPT_LOW_SPEED_TIME => $config->lowSpeedTime, CURLOPT_SSL_VERIFYHOST => $config->sslVerifyHost, CURLOPT_SSL_VERIFYPEER => $config->sslVerifyPeer, CURLOPT_FAILONERROR => false, CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS]); if ($config->proxy !== null) { $proxy = $config->getProxyInfo(); curl_setopt_array($this->handle, [CURLOPT_PROXY => $proxy['ip'], CURLOPT_PROXYPORT => $proxy['port'], CURLOPT_PROXYTYPE => $proxy['type'], CURLOPT_PROXYUSERPWD => $proxy['login']]); } if ($config->progressHandler !== null && !$config->headersOnly) { curl_setopt_array($this->handle, [CURLOPT_NOPROGRESS => false, CURLOPT_PROGRESSFUNCTION => function ($curl, $dltotal, $dlnow, $ultotal, $ulnow) use($config) { return call_user_func_array($config->progressHandler, [$dltotal, $dlnow, $ultotal, $ulnow]); }]); } $response = new CurlResponse($this->handle, clone $config, curl_exec($this->handle)); if ($response->getFailed()) { if ($config->throwException && $response->getTooManyRedirects()) { throw new TooManyRedirectsException($response, "The request failed due to too many redirects.", $response->errorNumber); } elseif ($config->throwException && $response->aborted) { throw new RequestAbortedException($response, "The request was aborted.", $response->errorNumber); } elseif ($config->retryHandler !== null && call_user_func_array($config->retryHandler, [$config, $response, $retryCount, time() - $startTime])) { $this->sendInternal($config, $startTime, ++$retryCount); } elseif ($config->throwException) { if ($response->getTimedOut()) { throw new RequestTimedOutException($response, "The request timed out.", $response->errorNumber); } else { throw new RequestFailedException($response, sprintf("The request failed: %s (#%d)", $response->error, $response->errorNumber), $response->errorNumber); } } } elseif (!empty($config->expectedHttpCodes) && !in_array($response->getHttpCode(), $config->expectedHttpCodes)) { throw new UnexpectedHttpCodeException($response, "Received an unexpected http code: {$response->getHttpCode()}", $response->errorNumber); } return $response; }
public function error() { $error = parent::error(); if ($error) { return $error; } if (!is_array($this->data)) { return sprintf('transloadit: bad response, no json: %s', $this->data); } if (array_key_exists('error', $this->data)) { $error = sprintf('transloadit: %s', $this->data['error']); if (array_key_exists('message', $this->data)) { $error .= sprintf(': %s', $this->data['message']); } if (array_key_exists('reason', $this->data)) { $error .= sprintf(': %s', $this->data['reason']); } return $error; } if (!array_key_exists('ok', $this->data)) { return 'transloadit: bad response data, no ok / error key included.'; } return false; }
/** * @param $url * @param string $method * @param null $content * @param null $headers * @param bool $followLoc * @return CurlResponse */ private function execCurl($url, $method = 'GET', $content = null, $headers = null, $followLoc = true) { $res = new CurlResponse(); if (isset($method)) { curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method); } curl_setopt($this->ch, CURLOPT_URL, $url); curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout); if (!empty($headers)) { curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers); } curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $followLoc ? 1 : 0); //支持跳转 //curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($res,'handleHeader')); // handle received headers curl_setopt($this->ch, CURLOPT_HEADER, true); if (!empty($content)) { $content_type = ''; // 取content-type foreach ($headers as $h) { list($n, $v) = explode(':', $h) + array(null, null); if (strcasecmp(trim($n), 'Content-Type') === 0) { $content_type = trim($v); break; } } if (is_array($content) && $content_type == 'application/json') { curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($content)); } else { if ($content_type == 'multipart/form-data') { curl_setopt($this->ch, CURLOPT_POSTFIELDS, $content); } else { if (is_array($content)) { curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($content)); } else { curl_setopt($this->ch, CURLOPT_POSTFIELDS, $content); } } } } $response = curl_exec($this->ch); $res->http_code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE); $res->errno = curl_errno($this->ch); $res->errstr = curl_error($this->ch); $res->parseReturnData($response); return $res; }
protected function doRequest($methode) { /* Construct field string like ?var1=val1&var2=val2... */ $fields_string = ""; if (is_array($this->arrParams)) { $fields_string = http_build_query($this->arrParams); } $isXmlToSend = isset($this->xmlToSend) && $this->xmlToSend != "" ? true : false; /* Init curl */ if ($methode == "GET") { if ($fields_string != "") { $fields_string = "?" . $fields_string; } echo "URL request [GET] : " . $this->url . $fields_string . "<br /><br />"; $process = curl_init($this->url . $fields_string); curl_setopt($process, CURLOPT_POST, 0); } else { if ($methode == "PUT") { if ($isXmlToSend) { if ($fields_string != "") { $fields_string = "?" . $fields_string; } $process = curl_init($this->url . $fields_string); echo "URL request [PUT] : " . $this->url . $fields_string . "<br /><br />"; } else { $process = curl_init($this->url); curl_setopt($process, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields_string))); } curl_setopt($process, CURLOPT_CUSTOMREQUEST, 'PUT'); } else { if ($isXmlToSend) { if ($fields_string != "") { $fields_string = "?" . $fields_string; } $process = curl_init($this->url . $fields_string); echo "URL request [POST] : " . $this->url . $fields_string . "<br /><br />"; } else { $process = curl_init($this->url); curl_setopt($process, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields_string))); } curl_setopt($process, CURLOPT_POST, 1); } } /* Send XML into body */ if ($isXmlToSend) { curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); curl_setopt($process, CURLOPT_POSTFIELDS, $this->xmlToSend); echo "XML request : <br /><textarea rows='5' cols='100'>" . $this->xmlToSend . "</textarea><br /><br />"; } curl_setopt($process, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($process, CURLOPT_CONNECTTIMEOUT, $this->timeout); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_USERPWD, $this->httpLogin . ":" . $this->httpPasswd); curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false); //check certificat /* Test connection to webservices, 10x */ for ($i = 0; $i < 10; $i++) { $resultReq = curl_exec($process); if ($resultReq === FALSE) { /* Wait one second to retry the connection */ sleep(1); $resultReq = null; } else { break; } } /* If you have not been able to connect 10 times, it throws an exception and stops */ if (!isset($resultReq)) { throw new Exception("error curl request (method=" . $methode . ") : '" . curl_error($process) . "'"); } $code = curl_getinfo($process, CURLINFO_HTTP_CODE); curl_close($process); $reqAction = $this->arrParams["action"]; $responseObj = new CurlResponse($reqAction, $code, $resultReq); echo "ResponseObject : <br /><textarea rows='5' cols='100'>" . $responseObj->getResponse() . "</textarea><br />Code return " . $responseObj->getCode() . "<br /><br />"; return $responseObj; }
/** * Makes an HTTP request of the specified $method to a $url with an optional array or string of $vars * * Returns a CurlResponse object if the request was successful, false otherwise * * @param string $method * @param string $url * @param array|string $vars * @return CurlResponse|boolean */ public function request($method, $url, $vars = array()) { $this->error = Null; $used_proxies = 0; if (is_array($vars)) { $this->vars = http_build_query($vars, '', '&'); } if (!is_string($url) and $url !== '') { throw new CurlException("Invalid URL: " . $url); } do { $this->closeRequest(); $this->request = curl_init(); if (count($this->proxies) > $used_proxies) { //$this->setOption['HTTPPROXYTUNNEL'] = True; $this->setOption('PROXY', $this->proxies[$used_proxies]['ip'] . ':' . $this->proxies[$used_proxies]['port']); $this->setOption('PROXYPORT', $this->proxies[$used_proxies]['port']); //$this->setOption('PROXYTYPE', CURLPROXY_HTTP); $this->setOption('TIMEOUT', $this->proxies[$used_proxies]['timeout']); if ($this->proxies[$used_proxies]['user'] !== NUll and $this->proxies[$used_proxies]['pass'] !== Null) { $this->setOption('PROXYUSERPWD', $this->proxies[$used_proxies]['user'] . ':' . $this->proxies[$used_proxies]['pass']); } $used_proxies++; } else { unset($this->option['PROXY'], $this->option['PROXYPORT'], $this->option['PROXYTYPE'], $this->option['PROXYUSERPWD']); } //debug::dump($this->options); $this->set_request_method($method); $this->set_request_options($url); $this->set_request_headers(); $response = curl_exec($this->request); $this->error = curl_errno($this->request) . ' - ' . curl_error($this->request); $this->info = curl_getinfo($this->request); } while (curl_errno($this->request) == 6 and count($this->proxies) < $used_proxies); $this->closeRequest(); if ($response) { $response = new CurlResponse($response, $this); $response_headers = $response->getHeaders(); if (isset($response_headers['Location']) and $this->getFollowRedirects()) { $response = $this->request($this->getMethod(), $response_headers['Location']); } } else { if ($this->info['http_code'] == 400) { throw new CurlException('Bad request - ' . $response); } elseif ($this->info['http_code'] == 401) { throw new CurlException('Permission Denied - ' . $response); } else { throw new CurlException($this->error); } } return $response; }
/** * @dataProvider stringProvider * * @param string $message */ public function testGetErrorMessage($message) { $response = new CurlResponse('', ['http_code' => 400], $message); $this->assertEquals($message, $response->getErrorMessage()); }