/** * @param string $url * @param mixed[]|null $body * @return \SlevomatZboziApi\Response\ZboziApiResponse */ public function sendPostRequest($url, array $body = null) { TypeValidator::checkString($url); $options = ['allow_redirects' => false, 'verify' => true, 'decode_content' => true, 'expect' => false, 'timeout' => $this->timeoutInSeconds]; $request = $this->client->createRequest('POST', $url, $options); $request->setHeaders([static::HEADER_PARTNER_TOKEN => $this->partnerToken, static::HEADER_API_SECRET => $this->apiSecret]); if ($body !== null) { $request->setBody(\GuzzleHttp\Stream\Stream::factory(json_encode($body))); } try { try { $response = $this->client->send($request); $this->log($request, $response); return $this->getZboziApiResponse($response); } catch (\GuzzleHttp\Exception\RequestException $e) { $response = $e->getResponse(); $this->log($request, $response); if ($response !== null) { return $this->getZboziApiResponse($response); } throw new \SlevomatZboziApi\Request\ConnectionErrorException('Connection to Slevomat API failed.', $e->getCode(), $e); } } catch (\GuzzleHttp\Exception\ParseException $e) { $this->log($request, isset($response) ? $response : null, true); throw new \SlevomatZboziApi\Response\ResponseErrorException('Slevomat API invalid response: invalid JSON data.', $e->getCode(), $e); } }
public function callApi($call, $method = 'GET', array $options = []) { $time = microtime(true); $request = $this->_guzzle->createRequest($method, $this->_baseUri . '/' . $call, $options); if ($this->_headers) { foreach ($this->_headers as $header => $value) { $request->addHeader($header, $value); } } if (!$this->isBatchOpen()) { try { return $this->_processResponse($this->_guzzle->send($request), $time); } catch (RequestException $e) { $response = $e->getResponse(); if ($response) { return $this->_processResponse($response, $time); } else { throw $e; } } } $batchId = uniqid($method, true); $request->addHeader('X-Batch-ID', $batchId); $apiResult = new ApiResult(); $this->_batch[] = $request; $this->_results[$batchId] = $apiResult; return $apiResult; }
public function testOnlyResponse() { $request = $this->guzzleHttpClient->createRequest('GET', 'http://petstore.swagger.io/v2/pet/findByStatus'); $request->addHeader('Accept', 'application/json'); $response = $this->guzzleHttpClient->send($request); $this->assertResponseMatch($response, self::$schemaManager, '/v2/pet/findByStatus', 'get'); }
/** * {@inheritdoc} */ public function fetch(FeedInterface $feed) { $request = $this->httpClient->createRequest('GET', $feed->getUrl()); $feed->source_string = FALSE; // Generate conditional GET headers. if ($feed->getEtag()) { $request->addHeader('If-None-Match', $feed->getEtag()); } if ($feed->getLastModified()) { $request->addHeader('If-Modified-Since', gmdate(DateTimePlus::RFC7231, $feed->getLastModified())); } try { $response = $this->httpClient->send($request); // In case of a 304 Not Modified, there is no new content, so return // FALSE. if ($response->getStatusCode() == 304) { return FALSE; } $feed->source_string = $response->getBody(TRUE); $feed->setEtag($response->getHeader('ETag')); $feed->setLastModified(strtotime($response->getHeader('Last-Modified'))); $feed->http_headers = $response->getHeaders(); // Update the feed URL in case of a 301 redirect. if ($response->getEffectiveUrl() != $feed->getUrl()) { $feed->setUrl($response->getEffectiveUrl()); } return TRUE; } catch (RequestException $e) { $this->logger->warning('The feed from %site seems to be broken because of error "%error".', array('%site' => $feed->label(), '%error' => $e->getMessage())); drupal_set_message(t('The feed from %site seems to be broken because of error "%error".', array('%site' => $feed->label(), '%error' => $e->getMessage())), 'warning'); return FALSE; } }
public function testFetchPetBodyMatchDefinition() { $request = $this->guzzleHttpClient->createRequest('GET', 'http://petstore.swagger.io/v2/pet/findByStatus'); $request->addHeader('Accept', 'application/json'); $response = $this->guzzleHttpClient->send($request); $responseBody = $response->json(['object' => true]); $this->assertResponseBodyMatch($responseBody, self::$schemaManager, '/v2/pet/findByStatus', 'get', 200); }
/** * Converts a PSR request into a Guzzle request. * * @param RequestInterface $request * * @return GuzzleRequest */ private function createRequest(RequestInterface $request) { $options = ['exceptions' => false, 'allow_redirects' => false]; $options['version'] = $request->getProtocolVersion(); $options['headers'] = $request->getHeaders(); $options['body'] = (string) $request->getBody(); return $this->client->createRequest($request->getMethod(), (string) $request->getUri(), $options); }
/** * @param string $method * @param string $path * @param array $options * * @return array */ public function sendRequest($method, $path, array $options = []) { try { $response = $this->handler->send($this->handler->createRequest($method, $path, $options)); } catch (ClientException $ex) { $response = $ex->getResponse(); } return $response->json(); }
private function sendRequest() { $url = self::ApiUrl . '/' . $this->request; $request = $this->client->createRequest('GET', $url); $request->addHeader('Content-Type', 'application/json'); $response = $this->client->send($request); $data = $response->json(); return new Response($data); }
/** * {@inheritdoc} */ public function queryCircle($url, $query_args = [], $method = 'GET', $request_options = []) { if (!isset($query_args['circle-token'])) { throw new \InvalidArgumentException('The circle-token is required for all endpoints.'); } $url .= '?' . http_build_query($query_args); $request = $this->httpClient->createRequest($method, $url, $request_options); $request->addHeaders(['Accept' => 'application/json']); return $this->httpClient->send($request)->json(); }
/** * {@inheritdoc } */ public function post($url, $body, array $files = array()) { $request = $this->httpClient->createRequest('POST', $url, ['body' => $body]); /** @var PostBodyInterface $postBody */ $postBody = $request->getBody(); foreach ($files as $key => $filePath) { $file = $this->postFileFactory->create($key, $filePath); $postBody->addFile($file); } $response = $this->httpClient->send($request); return $response; }
/** * @param string $endpoint * @param string $content * @param array $headers * @param array $files * @return Response */ public function send($endpoint, $content, array $headers = array(), array $files = array()) { $request = $this->client->createRequest('POST', $endpoint, array('body' => $content, 'exceptions' => false, 'headers' => $headers)); $body = new PostBody(); if ($files && $request instanceof RequestInterface) { foreach ($files as $name => $path) { $body->addFile(new PostFile($name, fopen($path, 'r'))); } } $request->setBody($body); $response = $this->client->send($request); return new Response($response->getStatusCode(), $response->getBody()); }
/** * {@inheritdoc} */ public function request($method, $url, $secret, array $params = []) { $options = ['auth' => [$secret, ''], 'connect_timeout' => 10, 'timeout' => 30, 'verify' => true]; if ('GET' !== $method) { $options['body'] = $params; } $request = $this->client->createRequest($method, $url, $options); try { $rawResponse = $this->client->send($request); } catch (RequestException $e) { $rawResponse = $this->handleException($e); } return new Response($rawResponse->getStatusCode(), $rawResponse->getBody()); }
/** * @param RequestInterface $request * * @return \GuzzleHttp\Message\RequestInterface */ protected function createGuzzleRequestFromRequest(RequestInterface $request) { $headers = array(); foreach ($request->getHeaders() as $headerName => $headerValue) { $headers[$headerName] = $headerValue[0]; } $headers['X-Forwarded-For'] = $request->getClientIp(); $headers['X-Forwarded-Proto'] = $request->getScheme(); if (isset($headers['cookie'])) { unset($headers['cookie']); } // see http://guzzle.readthedocs.org/en/latest/clients.html#request-options $guzzleRequest = $this->client->createRequest($request->getMethod(), $request->getUri(), array('headers' => $headers, 'body' => $request->getBody(), 'query' => $request->getQueryParams(), 'cookies' => $request->getCookies(), 'exceptions' => false, 'decode_content' => true)); return $guzzleRequest; }
function it_should_post_an_url(ClientInterface $handler, RequestInterface $request, ResponseInterface $response) { $options = ['body' => 'foo']; $handler->createRequest('POST', 'foo', $options)->willReturn($request); $handler->send($request)->shouldBeCalled(); $handler->send($request)->willReturn($response); $this->post('foo', $options); }
/** * @param string $method * @param array $payload * * @return RequestInterface */ private function createRequest($method, array $payload) { $request = $this->client->createRequest('POST'); $request->setUrl(self::API_BASE_URL . $method); $body = new PostBody(); $body->replaceFields($payload); $request->setBody($body); return $request; }
/** * Send a POST request to activeCollab * @param $path * @param array $data * @return object * @throws Exception\ApiException * @throws Exception\AuthenticationFailedException */ public function post($path, array $data = array()) { // Apparently the activeCollab API requires this if (!isset($data['submitted'])) { $data['submitted'] = 'submitted'; } $request = $this->client->createRequest('POST', null, ['body' => $data]); $request->setQuery(['path_info' => $path]); return $this->send($request); }
/** * Run request to Restoration Media */ public function send() { $request = $this->client->createRequest('GET', $this->getBuiltUrl()); $request->setHeader('User-Agent', 'github.com/caseyw/restorationmedia_php'); $this->response = $this->client->send($request); /* * Restoration Media doesn't actually use HTTP Status Codes. I don't know why. */ return 'success.' == $this->response->xml() ? true : false; }
/** * Sends HTTP request to specific path with body wrapped by field. * * @param string $method * @param string $path * @param string $field * @param TableNode $table * * @When /^(?:I )?send a (PUT|PATCH|POST) request to path "([^"]+)" with field (\w+)$/ */ public function iSendARequestWithField($method, $path, $field, TableNode $table = null) { $url = $this->getUrlFromPath($path, $method); $request = $this->client->createRequest($method, $url, ['headers' => $this->getHeadersBag()->all()]); if (null !== $table) { $body = new PostBody(); $body->replaceFields([$field => $table->getRowsHash()]); $request->setBody($body); } $this->send($request); }
private function createGuzzleRequest(Psr7Request $psrRequest, array $options) { $ringConfig = []; // Remove unsupported options. foreach (array_keys($options) as $key) { if (!isset(self::$validOptions[$key])) { unset($options[$key]); } } // Handle delay option. if (isset($options['delay'])) { $ringConfig['delay'] = $options['delay']; unset($options['delay']); } // Prepare sink option. if (isset($options['sink'])) { $ringConfig['save_to'] = $options['sink'] instanceof Psr7StreamInterface ? new GuzzleStream($options['sink']) : $options['sink']; unset($options['sink']); } // Ensure that all requests are async and lazy like Guzzle 6. $options['future'] = 'lazy'; // Create the Guzzle 5 request from the provided PSR7 request. $request = $this->client->createRequest($psrRequest->getMethod(), $psrRequest->getUri(), $options); // For the request body, adapt the PSR stream to a Guzzle stream. $body = $psrRequest->getBody(); if ($body->getSize() === 0) { $request->setBody(null); } else { $request->setBody(new GuzzleStream($body)); } $request->setHeaders($psrRequest->getHeaders()); $request->setHeader('User-Agent', 'aws-sdk-php/' . Sdk::VERSION . ' ' . Client::getDefaultUserAgent()); // Make sure the delay is configured, if provided. if ($ringConfig) { foreach ($ringConfig as $k => $v) { $request->getConfig()->set($k, $v); } } return $request; }
/** * Send HTTP request * @param string $method POST|GET * @param string $url http URL * @param array $options query options. Query values goes under 'body' key. * Example: * $options = [ * 'query' => [ * 'access_token' => 'foobar', * ], * 'body' => [ * 'param1' => 'value1', * 'param2' => 'value2', * ] * ] * @return array */ public function sendRequest($method, $url, array $options = []) { $result = []; try { $response = $this->client->send($this->client->createRequest($method, $url, $options)); $result = $response->json(); } catch (ClientException $e) { if ($e->getCode() == 400) { throw new Exception\InvalidData('Data validation failed', 400, $e, $e->getResponse()->json()); } elseif ($e->getCode() == 403) { throw new Exception\InvalidApiKey('Access forbidden. Invalid API key.', 403, $e, $e->getResponse()->getBody()); } elseif ($e->getCode() == 500) { throw new Exception\ServerError('Error occurred on server side while handling request', 500, $e, $e->getResponse()->getBody()); } elseif ($e->getCode() == 504) { throw new Exception\Timeout('Request timeout', 504, $e, $e->getResponse()->getBody()); } else { throw new Exception\UnexpectedResponse('Unexpected error occurred', $e->getCode(), $e, $e->getResponse()->getBody()); } } catch (\Exception $e) { throw new Exception\UnexpectedError('Unexpected error occurred', 0, $e); } return $result; }
/** * Sends HTTP request to specific URL with form data from PyString. * * @param string $method request method * @param string $url relative url * @param PyStringNode $body request body * * @When /^(?:I )?send a ([A-Z]+) request to "([^"]+)" with form data:$/ */ public function iSendARequestWithFormData($method, $url, PyStringNode $body) { $url = $this->prepareUrl($url); $body = $this->replacePlaceHolder(trim($body)); $fields = array(); parse_str(implode('&', explode("\n", $body)), $fields); $this->request = $this->client->createRequest($method, $url); /** @var \GuzzleHttp\Post\PostBodyInterface $requestBody */ $requestBody = $this->request->getBody(); foreach ($fields as $key => $value) { $requestBody->setField($key, $value); } $this->sendRequest(); }
/** * Create a Guzzle5 request object * * @param RequestInterface $request * @param bool $async * @return Request */ private function createRequest(RequestInterface $request, $async = false) { $body = Stream::factory($request->getBody()); $uri = (string) $request->getUri(); $headers = $request->getHeaders(); // fixes issue with host getting applied twice if (isset($headers['Host'])) { unset($headers['Host']); } $options = $async ? ['future' => true] : []; $request = $this->client->createRequest($request->getMethod(), $uri, $options); $request->setBody($body); $request->setHeaders(array_merge($request->getHeaders(), $headers)); return $request; }
private function createGuzzleRequest(Psr7Request $psrRequest, array $options) { $ringConfig = []; $statsCallback = isset($options['http_stats_receiver']) ? $options['http_stats_receiver'] : null; unset($options['http_stats_receiver']); // Remove unsupported options. foreach (array_keys($options) as $key) { if (!isset(self::$validOptions[$key])) { unset($options[$key]); } } // Handle delay option. if (isset($options['delay'])) { $ringConfig['delay'] = $options['delay']; unset($options['delay']); } // Prepare sink option. if (isset($options['sink'])) { $ringConfig['save_to'] = $options['sink'] instanceof Psr7StreamInterface ? new GuzzleStream($options['sink']) : $options['sink']; unset($options['sink']); } // Ensure that all requests are async and lazy like Guzzle 6. $options['future'] = 'lazy'; // Create the Guzzle 5 request from the provided PSR7 request. $request = $this->client->createRequest($psrRequest->getMethod(), $psrRequest->getUri(), $options); if (is_callable($statsCallback)) { $request->getEmitter()->on('end', function (EndEvent $event) use($statsCallback) { $statsCallback($event->getTransferInfo()); }); } // For the request body, adapt the PSR stream to a Guzzle stream. $body = $psrRequest->getBody(); if ($body->getSize() === 0) { $request->setBody(null); } else { $request->setBody(new GuzzleStream($body)); } $request->setHeaders($psrRequest->getHeaders()); $request->setHeader('User-Agent', $request->getHeader('User-Agent') . ' ' . Client::getDefaultUserAgent()); // Make sure the delay is configured, if provided. if ($ringConfig) { foreach ($ringConfig as $k => $v) { $request->getConfig()->set($k, $v); } } return $request; }
/** * calls every given url with the specific shop cookie * * @param string[] $urls * @param integer $shopId */ public function callUrls($urls, $shopId) { $shop = $this->getShopDataById($shopId); $guzzleConfig = []; if (!empty($shop["main_id"])) { //is not the main shop call url without shop cookie encoded in it $guzzleConfig['cookies'] = ['shop' => $shopId]; } foreach ($urls as $url) { $request = $this->guzzleClient->createRequest('GET', $url, $guzzleConfig); try { $this->guzzleClient->send($request); } catch (\Exception $e) { $this->logger->error("Warm up http-cache error with shopId " . $shopId . " " . $e->getMessage()); } } }
/** * Method returns the response for the requested resource. * * @param string $pURL * @param array $pOptions * * @return mixed */ protected function requestResource($pURL, array $pOptions) { $options = array_replace_recursive($this->settings['defaults'], $pOptions); $format = $options['format']; $method = $options['method']; $this->setHeaders($options); $parameters['headers'] = $this->headers; if (isset($options['body'])) { $parameters['body'] = $this->formatBody($options); } $request = $this->client->createRequest($method, $pURL, $parameters); try { $response = $this->client->send($request); $this->event->fire('forrest.response', [$request, $response]); return $this->responseFormat($response, $format); } catch (RequestException $e) { $this->assignExceptions($e); } return ''; }
/** * Creates a request. * * @param \Ivory\HttpAdapter\Message\InternalRequestInterface $internalRequest The internal request. * @param callable|null $success The success callable. * @param callable|null $error The error callable. * * @return \GuzzleHttp\Message\RequestInterface The request. */ private function createRequest(InternalRequestInterface $internalRequest, $success = null, $error = null) { $request = $this->client->createRequest($internalRequest->getMethod(), (string) $internalRequest->getUrl(), array('exceptions' => false, 'allow_redirects' => false, 'timeout' => $this->getConfiguration()->getTimeout(), 'connect_timeout' => $this->getConfiguration()->getTimeout(), 'version' => $internalRequest->getProtocolVersion(), 'headers' => $this->prepareHeaders($internalRequest), 'body' => $this->prepareContent($internalRequest))); if (is_callable($success)) { $messageFactory = $this->getConfiguration()->getMessageFactory(); $request->getEmitter()->on('complete', function (CompleteEvent $event) use($success, $internalRequest, $messageFactory) { $response = $messageFactory->createResponse((int) $event->getResponse()->getStatusCode(), $event->getResponse()->getReasonPhrase(), $event->getResponse()->getProtocolVersion(), $event->getResponse()->getHeaders(), BodyNormalizer::normalize(function () use($event) { return new GuzzleHttpStream($event->getResponse()->getBody()); }, $internalRequest->getMethod())); $response->setParameter('request', $internalRequest); call_user_func($success, $response); }); } if (is_callable($error)) { $httpAdapterName = $this->getName(); $request->getEmitter()->on('error', function (ErrorEvent $event) use($error, $internalRequest, $httpAdapterName) { $exception = HttpAdapterException::cannotFetchUrl($event->getException()->getRequest()->getUrl(), $httpAdapterName, $event->getException()->getMessage()); $exception->setRequest($internalRequest); call_user_func($error, $exception); }); } return $request; }
public function post($urlPath, array $parameters = [], $body) { $request = $this->httpClient->createRequest('POST', array(), array('body' => $body)); $url = rtrim($this->getBaseUrl(), '/') . '/' . trim($urlPath, '/'); $request->setUrl($url); // Set the API key in a header instead of a URL parameter, so it will // not accidentally end up in log messages. $request->setHeader('X-IZI-API-KEY', $this->apiKey); // Add compression. $this->addCompression($request); // For some strange reason, for the first post request (reviews) // we need to add the api-key to the url. // It might change, so when that is happening, you are free to alter this here. // Mind to test the posting of reviews again if you change it. $parameters['api_key'] = $this->apiKey; $parameters['version'] = ApiInterface::VERSION; $request->getQuery()->replace($parameters); $request->getQuery()->setAggregator(static::getGuzzleQueryAggregator()); $pre_request_event = new PreRequest($request); $this->eventDispatcher->dispatch(IziTravelEvents::PRE_REQUEST, $pre_request_event); try { $response = $this->httpClient->send($request); $post_response_event = new PostResponse($response); $this->eventDispatcher->dispatch(IziTravelEvents::POST_RESPONSE, $post_response_event); $json = $response->getBody()->getContents(); } catch (\Exception $e) { throw new HttpRequestException(sprintf('An exception was thrown during the API request to %s: %s', $request->getUrl(), $e->getMessage()), 0, $e); } $responseData = json_decode($json); if (json_last_error()) { throw new HttpRequestException(sprintf('The request to %s did not return valid JSON.', $request->getUrl())); } elseif (is_array($responseData) && isset($responseData['error'])) { throw new ErrorResponseException($responseData['error'], $responseData['code']); } else { return $json; } }
/** * @param string $method * @param array $data * @param string|null $token * * @throws SlackException * * @return array */ private function doSend($method, array $data, $token = null) { try { $data['token'] = $token ?: $this->token; $this->eventDispatcher->dispatch(self::EVENT_REQUEST, new RequestEvent($data)); $request = $this->client->createRequest('POST', self::API_BASE_URL . $method); $body = new PostBody(); $body->replaceFields($data); $request->setBody($body); $response = $this->client->send($request); } catch (\Exception $e) { throw new SlackException('Failed to send data to the Slack API', null, $e); } try { $responseData = json_decode($response->getBody(), true); if (!is_array($responseData)) { throw new \Exception(sprintf('Expected JSON-decoded response data to be of type "array", got "%s"', gettype($responseData))); } $this->eventDispatcher->dispatch(self::EVENT_RESPONSE, new ResponseEvent($responseData)); return $responseData; } catch (\Exception $e) { throw new SlackException('Failed to process response from the Slack API', null, $e); } }
/** * @param Schedule $schedule * @return \GuzzleHttp\Message\RequestInterface */ public function buildSearchRequest(Schedule $schedule) { $rawXmlRequest = <<<XML <?xml version="1.0" encoding="UTF-8"?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://tempuri.org/" xmlns:ns2="http://www.w3.org/2005/08/addressing"> <env:Header> <ns2:Action env:mustUnderstand="true">http://tempuri.org/IWSVentaOnline/ObtenerTarifas</ns2:Action> <ns2:To env:mustUnderstand="true">{$this->config["url"]}</ns2:To> </env:Header> <env:Body> <ns1:ObtenerTarifas> <ns1:strOrigen>{$schedule->getFrom()}</ns1:strOrigen> <ns1:strDestino>{$schedule->getTo()}</ns1:strDestino> <ns1:strFecha>{$schedule->getDatetime()->format('Y-m-d')}</ns1:strFecha> </ns1:ObtenerTarifas> </env:Body> </env:Envelope> XML; $header = 'application/soap+xml; charset=utf-8; action="http://tempuri.org/IWSVentaOnline/ObtenerTarifas"'; return $this->httpClient->createRequest('POST', $this->config['endpoint'], ['body' => $rawXmlRequest, 'headers' => ['Content-type' => $header]]); }
public function it_returns_a_resource(ClientInterface $mockedClient, StorageInterface $mockedStorage, RequestInterface $mockedRequest, ResponseInterface $mockedResponse) { $mockedClient->createRequest(Argument::type('string'), Argument::type('string'), Argument::type('array'))->willReturn($mockedRequest); $mockedClient->send(Argument::any())->willReturn($mockedResponse); $mockedResponse->json()->shouldBeCalled()->willReturn('jsonResource'); $mockedResponse->xml()->shouldBeCalled()->willReturn('xmlResource'); $mockedStorage->getTokenData()->willReturn(['access_token' => 'abc', 'instance_url' => 'def', 'token_type' => 'bearer']); $this->request('uri', [])->shouldReturn('jsonResource'); $this->request('uri', ['format' => 'xml'])->shouldReturn('xmlResource'); }