• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP GuzzleHttp\ClientInterface类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中GuzzleHttp\ClientInterface的典型用法代码示例。如果您正苦于以下问题:PHP ClientInterface类的具体用法?PHP ClientInterface怎么用?PHP ClientInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ClientInterface类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
 }
开发者ID:boxrice007,项目名称:openstack,代码行数:10,代码来源:Operator.php


示例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);
 }
开发者ID:xotelia,项目名称:streak-php-client,代码行数:7,代码来源:ClientSpec.php


示例3: __construct

 /**
  * @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);
 }
开发者ID:Rayac,项目名称:search,代码行数:38,代码来源:Pool.php


示例4: 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);
     }
 }
开发者ID:vierbergenlars,项目名称:authserver-client,代码行数:7,代码来源:LoadableTrait.php


示例5: 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();
 }
开发者ID:sroze,项目名称:tolerance,代码行数:14,代码来源:RabbitMqHttpClient.php


示例6: get

 public function get($url)
 {
     if (!$this->isValidArgument($url)) {
         throw new \InvalidArgumentException('Supply a valid URL please.');
     }
     return $this->guzzle->request("GET", $url);
 }
开发者ID:vinaykevadia,项目名称:moz,代码行数:7,代码来源:GuzzleClient.php


示例7: 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');
 }
开发者ID:Beanhunter,项目名称:SwaggerAssertions,代码行数:7,代码来源:GuzzleTest.php


示例8: 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());
 }
开发者ID:treehouselabs,项目名称:io-bundle,代码行数:25,代码来源:GuzzleClientTest.php


示例9: 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;
     }
 }
开发者ID:progrupa,项目名称:MailjetBundle,代码行数:33,代码来源:AbstractApi.php


示例10: 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();
 }
开发者ID:addrever,项目名称:ecat,代码行数:34,代码来源:Guzzle.php


示例11: 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());
 }
开发者ID:VinniaAB,项目名称:social-tools,代码行数:13,代码来源:TwitterClient.php


示例12: 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);
 }
开发者ID:easybiblabs,项目名称:oauth2-client-php,代码行数:10,代码来源:TokenRefreshRequest.php


示例13: 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;
 }
开发者ID:peak-adventure-travel,项目名称:rocketeer-flowdock,代码行数:37,代码来源:RocketeerFlowdockMessage.php


示例14: 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();
 }
开发者ID:fideloper,项目名称:DigitalOceanV2,代码行数:10,代码来源:Guzzle5Adapter.php


示例15: 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;
 }
开发者ID:jdi,项目名称:tntaffiliate,代码行数:28,代码来源:ApiClient.php


示例16: 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;
 }
开发者ID:degaray,项目名称:openpay-php-client,代码行数:38,代码来源:OpenpayAdapterAbstract.php


示例17: fetch

 /**
  * {@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;
     }
 }
开发者ID:davidsoloman,项目名称:drupalconsole.com,代码行数:36,代码来源:DefaultFetcher.php


示例18: sendPostRequest

 /**
  * @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);
     }
 }
开发者ID:pepakriz,项目名称:zbozi-api-php-library,代码行数:32,代码来源:RequestMaker.php


示例19: fetchPageContentFor

 /**
  * 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();
 }
开发者ID:dilipgurung,项目名称:sainsburys-page-scraper,代码行数:13,代码来源:LinkScraper.php


示例20: downloadFile

 /**
  * 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;
     }
 }
开发者ID:jacobjjc,项目名称:PageKit-framework,代码行数:33,代码来源:PackageDownloader.php



注:本文中的GuzzleHttp\ClientInterface类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP GuzzleHttp\HandlerStack类代码示例发布时间:2022-05-23
下一篇:
PHP GuzzleHttp\Client类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap