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 $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; }
/** * 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 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()); }
/** * 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(); }
public function get($url) { if (!$this->isValidArgument($url)) { throw new \InvalidArgumentException('Supply a valid URL please.'); } return $this->guzzle->request("GET", $url); }
/** * @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; } }
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); }
/** * {@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); }
/** * @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); }
public function it_includes_parameters(HttpClient $client, Response $response) { $url = 'http://www.example.com'; $params = ['foo' => 'bar']; $client->request('get', $url, ['query' => $params])->shouldBeCalled(); $client->request('get', $url, ['query' => $params])->willReturn($response); $this->get($url, $params)->shouldHaveType(GuzzleResponseAdapter::class); }
/** * Will perform a $verb request to the given $endpoint with $parameters. * * @param string $endpoint Url where curly braces will be replaces, Ex: add/{id}/something * @param string $verb May be get, delete, head, options, patch, post, put * @param array $parameters Array of parameters, Ex: ['id' => 5, 'name' => 'john doe'] * * @throws RequestException * * @return array Response data */ public function request($endpoint, $verb = 'get', array $parameters = []) { try { return $this->client->request($verb, $endpoint, $parameters); } catch (GuzzleException $error) { throw new RequestException((string) $error->getResponse()->getBody(), $error->getCode()); } }
/** * @param string $apiKey * @param string $apiSecret * @param string $username * @param string $password * * @return AccessToken */ public function getAccessToken($apiKey, $apiSecret, $username, $password) { $response = $this->guzzle->request('POST', self::ENDPOINT, ['auth' => [$apiKey, $apiSecret], 'form_params' => ['grant_type' => 'password', 'username' => $username, 'password' => $password]]); $data = json_decode((string) $response->getBody(), true); $token = $data['access_token']; $expiry = new \DateTime('@' . (time() + $data['expires_in'])); return new AccessToken($token, $expiry); }
/** * Calls the method contained in the actions of this resource * @param string $method * @param array $args * @return \StdClass The JSON decoded response */ public function __call($method, $args) { $action = $this->getActions()[$method]; $uri = $this->getBaseUri() . $this->getPath($action, $args); $params = $this->getParams($args); $this->last_response = $this->client->request($action['method'], $uri, $params); return json_decode($this->last_response->getBody()); }
/** * 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); }
/** * {@inheritdoc} */ public function call($method, $uri, array $options = []) { $exceptionFactory = new ExceptionFactory(); try { return $this->httpClient->request($method, $uri, $options); } catch (ClientException $baseException) { throw $exceptionFactory->create($baseException); } }
/** * @param UriInterface $httpUri * @param string $method * @param array $data [OPTIONAL] * * @return array */ protected function proceed(UriInterface $httpUri, $method, array $data = []) { if (!empty($data)) { $response = $this->httpClient->request($method, $httpUri, ['headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], 'body' => 'JSONString=' . \GuzzleHttp\json_encode($data)]); } else { $response = $this->httpClient->request($method, $httpUri); } return \GuzzleHttp\json_decode($response->getBody()->getContents()); }
public function query($projectionName, $partition = null) { $url = sprintf('%s/projection/%s', $this->url, $projectionName); if ($partition) { $url .= "?q=" . $partition; } $response = $this->httpClient->request('GET', $url); return json_decode($response->getBody(), true); }
/** * @param Busca $busca * @return array * @throws APIException */ public function enviar(Busca $busca) { $resposta = $this->http->request('POST', self::ENDPOINT, ['body' => json_encode($this->normalize($busca))]); $dados = json_decode($resposta->getBody()->getContents(), true); if ($dados['Status']['Erro']) { throw new APIException('Api error'); } return $dados['Trechos']; }
/** * @param RequestInterface $request * * @return ResponseInterface * * @throws ApiException | SearchLimitException */ public function research(RequestInterface $request) { try { $response = $this->httpClient->request('GET', Uri::withQueryValue($request->getUri(), 'apikey', $this->apiKey)); return new Response($response); } catch (\GuzzleHttp\Exception\ClientException $ex) { throw ExceptionFactory::createThrowable($ex); } }
/** * @param string $url * @param array $form * @return array */ private function makeRequest($url, array $form = null) { $options = ['query' => ['apikey' => $this->apiKey]]; if (null !== $form) { $options['query'] += $form; } $response = $this->guzzle->request('GET', $url, $options); return json_decode((string) $response->getBody(), true); }
/** * @param $method * @param null $uri * @param array $options * @return \Psr\Http\Message\ResponseInterface */ protected function request($method, $uri = null, array $options = []) { if (null !== $this->token) { $options = array_merge($options, ['headers' => ['Authorization' => sprintf('Bearer %s', $this->token)]]); } $this->log(sprintf('Uri: %s, Method: %s, Options: %s', $uri, $method, \GuzzleHttp\json_encode($options))); $response = $this->client->request($method, $uri, $options); return $response; }
/** * Retrieve the job feed associated with the configured company ID * * @param array $filters Optional filters with keys found in self::JOB_FEED_FILTERS * @return string * @throws Exception\JobviteException */ public function getJobFeed(array $filters = []) { $response = $this->client->request('GET', '/v1/jobFeed', ['base_uri' => $this->baseUri, 'query' => $this->buildQuery($filters, self::JOB_FEED_FILTERS)]); try { return \GuzzleHttp\json_decode((string) $response->getBody()); } catch (\InvalidArgumentException $invalidArgumentException) { throw new Exception\JobviteException('Unable to decode response as JSON.', 0, $invalidArgumentException); } }
/** * Before outputting custom links, it is validated to ensure that the user is not * directed off to a broken link. If a 404 is detected, it is hidden. * * @param $link The proposed link * * @return bool */ private function linkIsValid(string $link) : bool { $link = $this->docDomain . $link; try { return $this->client->request('HEAD', $link)->getStatusCode() < 400; } catch (ClientException $e) { return false; } }
public function request(Query $query, $params = []) { $params['format'] = 'json'; $params['q'] = $query->getQuery(); $queryString = $this->buildHttpQueryString($params); $response = $this->client->request('GET', $this->buildBaseUrl() . '?' . $queryString); $rawContents = GuzzleHttp\json_decode($response->getBody()->getContents()); return $rawContents->query; }
/** * {@inheritdoc} */ public function get() { try { $response = $this->client->request('GET', '/'); } catch (TransferException $e) { throw new ApiException($e->getMessage(), 0, $e); } return $response->getBody()->getContents(); }
/** * Before outputting custom links, it is validated to ensure that the user is not * directed off to a broken link. If a 404 is detected, it is hidden. * * @param $link The proposed link * * @return bool */ private function linkIsValid($link) { $link = $this->docDomain . $link; try { $resp = $this->client->request('HEAD', $link); } catch (ClientException $e) { } return $resp->getStatusCode() < 400; }
/** * @param $url * @param array $headers * @return \Psr\Http\Message\ResponseInterface * @throws \RuntimeException */ private function getUrl($url, $headers = []) { $jar = new CookieJar(); $res = $this->httpClient->request('GET', $url, ['headers' => $headers, 'cookies' => $jar]); if ($res->getStatusCode() != 200) { throw new \RuntimeException('Error ' . $res->getStatusCode() . 'while get url ' . $url); } sleep($this->requestDelay); return $res; }
/** * @inheritdoc */ public function send($method, $uri, $body = null, array $query = [], array $headers = [], array $options = []) { $options = array_merge($options, [RequestOptions::QUERY => $query, RequestOptions::HEADERS => $headers]); if (!empty($body) && (is_array($body) || $body instanceof \JsonSerializable)) { $options[RequestOptions::JSON] = $body; } else { $options[RequestOptions::BODY] = $body; } return $this->guzzleClient->request($method, $uri, $options); }
/** * @param string $url * @param array $json * @return array */ private function makeRequest($url, array $json = null) { $method = 'GET'; $options = ['query' => ['token' => $this->accessToken->getToken()]]; if (null !== $json) { $method = 'POST'; $options['json'] = $json; } $response = $this->guzzle->request($method, $url, $options); return json_decode((string) $response->getBody(), true); }