private function loadSelf() { if ($this->_client && $this->_links && isset($this->_links['self']) && isset($this->_links['self']['href'])) { $data = json_decode($this->_client->request('GET', $this->_links['self']['href'])->getBody(), true); $this->setFromApiData($data); } }
/** * @param string $vhost * @param string $name * @param int $interval * * @return array */ public function getQueue($vhost, $name, $interval = 30) { $queueName = sprintf('%s/%s', urlencode($vhost), urlencode($name)); $url = sprintf('http://%s:%d/api/queues/%s?%s', $this->hostname, $this->port, $queueName, http_build_query(['lengths_age' => $interval, 'lengths_incr' => $interval, 'msg_rates_age' => $interval, 'msg_rates_incr' => $interval, 'data_rates_age' => $interval, 'data_rates_incr' => $interval])); $response = $this->httpClient->get($url, ['auth' => [$this->user, $this->password]]); return $response->json(); }
public function get($url) { if (!$this->isValidArgument($url)) { throw new \InvalidArgumentException('Supply a valid URL please.'); } return $this->guzzle->request("GET", $url); }
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'); }
public function testFetch() { $url = 'http://google.com'; $redirect = 'https://www.google.com'; $ua = 'IO Crawler/1.0'; $body = 'test'; $headers = ['content-length' => [1234], 'content-type' => ['text/plain']]; $response = new GuzzleResponse(200, $headers, $body); $this->guzzle->expects($this->once())->method('request')->with('GET', $url, $this->callback(function (array $options) use($ua) { $this->assertArraySubset(['headers' => ['User-Agent' => $ua]], $options); return true; }))->will($this->returnCallback(function () use($url, $redirect, $response) { $this->client->setEffectiveUri($url, $redirect); return $response; })); $result = $this->client->fetch($url, $ua); $this->assertInternalType('array', $result); $this->assertCount(2, $result); /** @var ResponseInterface $response */ list($effectiveUrl, $response) = $result; $this->assertEquals($redirect, $effectiveUrl); $this->assertInstanceOf(ResponseInterface::class, $response); $this->assertArraySubset($headers, $response->getHeaders()); $this->assertEquals($body, $response->getBody()->getContents()); }
/** * @param $id * @return Result */ protected function call($method, $resource, $body = null, $acceptedCodes = array(200)) { try { $response = $this->client->request($method, $resource, array('body' => $body)); $responseBody = (string) $response->getBody(); if ($responseBody) { /** @var Result $result */ $result = $this->serializer->deserialize($responseBody, $this->getResultClass(), 'json'); $result->deserializeData($this->serializer, $this->getModel()); } else { $result = new Result(); } $result->setSuccess(in_array($response->getStatusCode(), $acceptedCodes))->setMessage($response->getReasonPhrase()); return $result; } catch (GuzzleException $ge) { if ($ge->getCode() == \Symfony\Component\HttpFoundation\Response::HTTP_TOO_MANY_REQUESTS && php_sapi_name() == "cli") { sleep(5); return $this->call($method, $resource, $body, $acceptedCodes); } else { $result = new Result(); $result->setSuccess(false)->setMessage(sprintf("Client error: %s", $ge->getMessage())); return $result; } } catch (\Exception $e) { $result = new Result(); $result->setSuccess(false)->setMessage(sprintf("General error: %s", $e->getMessage())); return $result; } }
/** * Fetches data from api * @param string $url * @param array $options * @throws ConnectionException * @throws HTTPException * @return string */ public function fetch($url, $options) { $request_type = $this->config->http_post === true ? 'form_params' : 'query'; $options = [$request_type => $options]; try { $response = $this->client->request($this->config->http_post === true ? 'POST' : 'GET', $url, $options); } catch (GuzzleException $exception) { throw new ConnectionException($exception->getMessage(), $exception->getCode()); } if ($response->getStatusCode() >= 400) { // ccp is using error codes even if they send a valid application // error response now, so we have to use the content as result // for some of the errors. This will actually break if CCP ever uses // the HTTP Status for an actual transport related error. switch ($response->getStatusCode()) { case 400: case 403: case 500: case 503: return $response->getBody()->getContents(); break; } throw new HTTPException($response->getStatusCode(), $url); } return $response->getBody()->getContents(); }
/** * @param string $method * @param string $endpoint * @param array $options * @return \stdClass */ protected function sendRequest($method, $endpoint, array $options = []) { $this->assertHasAccessToken(); $opts = array_merge_recursive(['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]], $options); $res = $this->httpClient->request($method, self::API_URL . $endpoint, $opts); return json_decode((string) $res->getBody()); }
/** * @return TokenResponse */ public function send() { $url = $this->serverConfig->getParams()['token_endpoint']; $params = [['name' => 'grant_type', 'contents' => self::GRANT_TYPE], ['name' => 'refresh_token', 'contents' => $this->refreshToken]]; $response = $this->httpClient->request('POST', $url, ['multipart' => $params]); return new TokenResponse($response); }
/** * Notifies the Flowdock channel of a deployment stage being initiated * * @param string $branchName * @param string $applicationName * @param string $connectionName * @param string $eventTitle * @param string $threadTitle * @return ResponseInterface * @throws FlowdockApiException */ public function notify($branchName, $applicationName, $connectionName, $eventTitle, $threadTitle) { if (empty($branchName)) { throw new \InvalidArgumentException('branchName is an Invalid Argument'); } if (empty($applicationName)) { throw new \InvalidArgumentException('applicationName is an Invalid Argument'); } if (empty($connectionName)) { throw new \InvalidArgumentException('connectionName is an Invalid Argument'); } if (empty($eventTitle)) { throw new \InvalidArgumentException('eventTitle is an Invalid Argument'); } if (empty($threadTitle)) { throw new \InvalidArgumentException('threadTitle is an Invalid Argument'); } $title = $this->formatEventTitle($branchName, $applicationName, $connectionName, $eventTitle); $body = json_encode(['flow_token' => $this->flowToken, 'event' => 'activity', 'author' => ['name' => get_current_user()], 'title' => $title, 'external_thread_id' => $this->externalThreadID, 'thread' => ['title' => $threadTitle, 'body' => '']]); $clientOptions = ['headers' => ['Content-Type' => 'application/json'], 'body' => $body]; $response = $this->client->post(self::MESSAGE_API, $clientOptions); if ($response->getStatusCode() != 202) { throw new FlowdockApiException("Error: HTTP " . $response->getStatusCode() . " with message " . $response->getReasonPhrase()); } return $response; }
/** * {@inheritdoc} */ public function post($url, array $headers = array(), $content = '') { $options = array('headers' => $headers, 'body' => $content); $request = $this->client->post($url, $options); $this->response = $request; return $this->response->getBody(); }
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; }
/** * @param string $url * @param array $options * @param string $method * @return array * @throws OpenpayException */ protected function callOpenpayClient($url, array $options, $method = self::GET_METHOD) { try { $rawResponse = $this->client->request($method, $url, $options); } catch (\Exception $e) { $responseParts = explode("\n", $e->getMessage()); $openpayException = new OpenpayException($responseParts[0], $e->getCode(), $e); if (!is_null($e->getResponse())) { $headers = $e->getResponse()->getHeaders(); } $values['error_code'] = isset($headers['OP-Error-Code']) ? $headers['OP-Error-Code'][0] : null; $values['request_id'] = isset($headers['OpenPay-Request-ID']) ? $headers['OpenPay-Request-ID'][0] : null; $dictionary = OpenpayExceptionsDictionary::get(); if (isset($dictionary[$values['error_code']])) { $values['description'] = $dictionary[$values['error_code']][self::DESCRIPTION_DICTIONARY_KEY]; } if (isset($responseParts[self::EXCEPTION_RESPONSE_JSON_INDEX])) { $responseObjectStr = $responseParts[self::EXCEPTION_RESPONSE_JSON_INDEX]; $responseObject = json_decode($responseObjectStr, self::JSON_DECODE_TO_ARRAY); // sometimes openpay response is a malformed json if (json_last_error() === JSON_ERROR_NONE) { $values = array_merge($values, $responseObject); } $openpayException = $this->exceptionMapper->create($values, $openpayException); } throw $openpayException; } $responseContent = $rawResponse->getBody()->getContents(); $responseArray = json_decode($responseContent, self::JSON_DECODE_AS_ARRAY); return $responseArray; }
/** * {@inheritDoc} */ public function __construct(ClientInterface $client, ApiInterface $api) { $this->client = $client; $this->api = $api; $this->errorBuilder = new Builder(); $this->client->getEmitter()->attach($this->errorBuilder); }
/** * {@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; } }
/** * @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); } }
/** * Scrape and fetch page content for the provided link * * @param $link * @return string */ public function fetchPageContentFor($link) { // We need to enable cookie to be able to get the proper page source $cookieJar = new CookieJar(); $response = $this->guzzleClient->get($link, ['cookies' => $cookieJar]); return (string) $response->getBody(); }
function it_should_get_a_raw_response(ClientInterface $handler, ResponseInterface $response) { $handler->request('GET', 'foo', [])->shouldBeCalled(); $handler->request('GET', 'foo', [])->willReturn($response); $response->getBody()->shouldBeCalled(); $this->get('foo', [], false); }
/** * Download a package file. * * @param string $path * @param string $url * @param string $shasum */ public function downloadFile($path, $url, $shasum = '') { $file = $path . '/' . uniqid(); try { $data = $this->client->get($url)->getBody(); if ($shasum && sha1($data) !== $shasum) { throw new ChecksumVerificationException("The file checksum verification failed"); } if (!$this->files->makeDir($path) || !$this->files->putContents($file, $data)) { throw new NotWritableException("The path is not writable ({$path})"); } if (Zip::extract($file, $path) !== true) { throw new ArchiveExtractionException("The file extraction failed"); } $this->files->delete($file); } catch (\Exception $e) { $this->files->delete($path); if ($e instanceof TransferException) { if ($e instanceof BadResponseException) { throw new UnauthorizedDownloadException("Unauthorized download ({$url})"); } throw new DownloadErrorException("The file download failed ({$url})"); } throw $e; } }
/** * Send request NIK * * @param string $nik * @return \Psr\Http\Message\ResponseInterface * @throws \InvalidArgumentException * @throws \GuzzleHttp\Exception\GuzzleException */ public function sendRequest($nik) { // Verify NIK $nik = $this->assertValidateNik($nik); $form_params = ['nik_global' => $nik, 'g-recaptcha-response' => ' ', 'wilayah_id' => '0', 'cmd' => 'Cari.']; return $this->client->request('POST', self::END_POINT, compact('form_params')); }
/** * @param VerifyYubikeyOtpCommand $command * @return YubikeyVerificationResult */ public function verify(VerifyYubikeyOtpCommand $command) { $this->logger->info('Verifying Yubikey OTP'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'otp' => ['value' => $command->otp]]; $response = $this->guzzleClient->post('api/verify-yubikey', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $type = $statusCode >= 400 && $statusCode < 500 ? 'client' : 'server'; $this->logger->info(sprintf('Yubikey OTP verification failed; %s error', $type)); return new YubikeyVerificationResult(true, false); } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('Yubikey OTP verification failed; server responded with malformed JSON.'); return new YubikeyVerificationResult(false, true); } if (!isset($result['status'])) { $this->logger->error('Yubikey OTP verification failed; server responded without status report.'); return new YubikeyVerificationResult(false, true); } if ($result['status'] !== 'OK') { $this->logger->error('Yubikey OTP verification failed; server responded with non-OK status report.'); return new YubikeyVerificationResult(false, true); } return new YubikeyVerificationResult(false, false); }
/** * {@inheritdoc} */ public function denormalize($data, $class, $format = NULL, array $context = array()) { $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody(); $path = 'temporary://' . drupal_basename($data['uri'][0]['value']); $data['uri'] = file_unmanaged_save_data($file_data, $path); return $this->entityManager->getStorage('file')->create($data); }
/** * @param \DonePM\ConsoleClient\Http\Commands\Command $command * * @return mixed|\Psr\Http\Message\ResponseInterface */ public function send(Command $command) { if ($command instanceof NeedsToken) { $command->token($this->token); } return $this->client->send($command->request()); }
/** * {@inheritDoc} */ public function request($method, $uri, array $parameters = []) { $itemEnvelope = null; if (isset($parameters['itemEnvelope'])) { $itemEnvelope = $parameters['itemEnvelope']; unset($parameters['itemEnvelope']); } try { $response = $this->guzzle->request($method, $uri, array_merge($this->params, $parameters)); } catch (ClientException $e) { if (!$e->hasResponse()) { throw $e; } throw $this->resolveExceptionClass($e); } catch (Exception $e) { throw $e; } $response = json_decode($response->getBody()->getContents(), true); if ($response === null) { $response = []; } if ($itemEnvelope) { $response['itemEnvelope'] = $itemEnvelope; } return Response::createFromJson($response); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $options = ['auth' => ['api', $this->key]]; $options['multipart'] = [['name' => 'to', 'contents' => $this->getTo($message)], ['name' => 'message', 'contents' => (string) $message, 'filename' => 'message.mime']]; return $this->client->post($this->url, $options); }
public function sendSms(SendSmsCommand $command) { $this->logger->info('Requesting Gateway to send SMS'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'message' => ['originator' => $command->originator, 'recipient' => $command->recipient, 'body' => $command->body]]; $response = $this->guzzleClient->post('api/send-sms', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $this->logger->error(sprintf('SMS sending failed, error: [%s] %s', $response->getStatusCode(), $response->getReasonPhrase()), ['http-body' => $response->getBody() ? $response->getBody()->getContents() : '']); return false; } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('SMS sending failed; server responded with malformed JSON.'); return false; } if (!isset($result['status'])) { $this->logger->error('SMS sending failed; server responded without status report.'); return false; } if ($result['status'] !== 'OK') { $this->logger->error('SMS sending failed; server responded with non-OK status report.'); return false; } return true; }
/** * @param ClientInterface $client Client used to send the requests. * @param array|\Iterator $requests Requests or functions that return * requests to send concurrently. * @param array $config Associative array of options * - concurrency: (int) Maximum number of requests to send concurrently * - options: Array of request options to apply to each request. * - fulfilled: (callable) Function to invoke when a request completes. * - rejected: (callable) Function to invoke when a request is rejected. */ public function __construct(ClientInterface $client, $requests, array $config = []) { // Backwards compatibility. if (isset($config['pool_size'])) { $config['concurrency'] = $config['pool_size']; } elseif (!isset($config['concurrency'])) { $config['concurrency'] = 25; } if (isset($config['options'])) { $opts = $config['options']; unset($config['options']); } else { $opts = []; } $iterable = \GuzzleHttp\Promise\iter_for($requests); $requests = function () use($iterable, $client, $opts) { foreach ($iterable as $key => $rfn) { if ($rfn instanceof RequestInterface) { (yield $key => $client->sendAsync($rfn, $opts)); } elseif (is_callable($rfn)) { (yield $key => $rfn($opts)); } else { throw new \InvalidArgumentException('Each value yielded by ' . 'the iterator must be a Psr7\\Http\\Message\\RequestInterface ' . 'or a callable that returns a promise that fulfills ' . 'with a Psr7\\Message\\Http\\ResponseInterface object.'); } } }; $this->each = new EachPromise($requests(), $config); }
/** * 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); }
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); }
/** * Perform the HTTP request * * @param string $method HTTP method/verb * @param string $url URL to send the request * @param array $parameters Key/Value pairs to form the query string * @param array $options Options to pass straight to GuzzleClient * * @return \Pisa\GizmoAPI\Adapters\GuzzleResponseAdapter */ public function request($method, $url, array $parameters = [], array $options = []) { if (!empty($parameters)) { $options['query'] = $this->fixParameters($parameters); } $response = $this->client->request($method, $url, $options); return new HttpResponse($response); }