本文整理汇总了PHP中GuzzleHttp\ClientInterface类的典型用法代码示例。如果您正苦于以下问题:PHP ClientInterface类的具体用法?PHP ClientInterface怎么用?PHP ClientInterface使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ClientInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* {@inheritDoc}
*/
public function __construct(ClientInterface $client, ApiInterface $api)
{
$this->client = $client;
$this->api = $api;
$this->errorBuilder = new Builder();
$this->client->getEmitter()->attach($this->errorBuilder);
}
示例2:
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);
}
示例3: loadSelf
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);
}
}
示例4: getQueue
/**
* @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();
}
示例5: get
public function get($url)
{
if (!$this->isValidArgument($url)) {
throw new \InvalidArgumentException('Supply a valid URL please.');
}
return $this->guzzle->request("GET", $url);
}
示例6: testOnlyResponse
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');
}
示例7: testFetch
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());
}
示例8: call
/**
* @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;
}
}
示例9: fetch
/**
* 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();
}
示例10: sendRequest
/**
* @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());
}
示例11: send
/**
* @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);
}
示例12: notify
/**
* 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;
}
示例13: post
/**
* {@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();
}
示例14: callApi
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;
}
示例15: callOpenpayClient
/**
* @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;
}