当前位置: 首页>>代码示例>>PHP>>正文


PHP Client::requestAsync方法代码示例

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


在下文中一共展示了Client::requestAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: importResource

 /**
  * @param string          $targetUrl   target url to import resource into
  * @param string          $file        path to file being loaded
  * @param OutputInterface $output      output of the command
  * @param Document        $doc         document to load
  * @param string          $host        host to import into
  * @param string          $rewriteHost string to replace with value from $host during loading
  * @param string          $rewriteTo   string to replace value from $rewriteHost with during loading
  * @param boolean         $sync        send requests syncronously
  *
  * @return Promise\Promise|null
  */
 protected function importResource($targetUrl, $file, OutputInterface $output, Document $doc, $host, $rewriteHost, $rewriteTo, $sync = false)
 {
     $content = str_replace($rewriteHost, $rewriteTo, $doc->getContent());
     $successFunc = function (ResponseInterface $response) use($output) {
         $output->writeln('<comment>Wrote ' . $response->getHeader('Link')[0] . '</comment>');
     };
     $errFunc = function (RequestException $e) use($output, $file) {
         $output->writeln('<error>' . str_pad(sprintf('Failed to write <%s> from \'%s\' with message \'%s\'', $e->getRequest()->getUri(), $file, $e->getMessage()), 140, ' ') . '</error>');
         if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
             $this->dumper->dump($this->cloner->cloneVar($this->parser->parse($e->getResponse()->getBody(), false, false, true)), function ($line, $depth) use($output) {
                 if ($depth > 0) {
                     $output->writeln('<error>' . str_pad(str_repeat('  ', $depth) . $line, 140, ' ') . '</error>');
                 }
             });
         }
     };
     if ($sync === false) {
         $promise = $this->client->requestAsync('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)]);
         $promise->then($successFunc, $errFunc);
     } else {
         $promise = new Promise\Promise();
         try {
             $promise->resolve($successFunc($this->client->request('PUT', $targetUrl, ['json' => $this->parseContent($content, $file)])));
         } catch (BadResponseException $e) {
             $promise->resolve($errFunc($e));
         }
     }
     return $promise;
 }
开发者ID:alebon,项目名称:import-export,代码行数:41,代码来源:ImportCommand.php

示例2: requestJsons

 /**
  * Create and send an HTTP request and return the decoded JSON response
  * body
  *
  * @throws EWSClientError
  *
  * @param string $method
  *   HTTP method e.g. GET, POST, DELETE
  * @param array  $uris
  *   URI strings
  * @param array  $options
  *   Request options to apply
  * @return mixed
  *   JSON decoded body from EWS
  */
 public function requestJsons($method, $uris, array $options = [])
 {
     // Add the OAuth access token to the request headers
     $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]);
     /** @var Promise\PromiseInterface[] $promises */
     $promises = [];
     $transactionIds = [];
     $counter = 0;
     foreach ($uris as $uri) {
         $transactionIds[] = Uuid::uuid4()->toString();
         $this->logRequest($transactionIds[$counter], $method, $uri, $options);
         $promises[] = $this->http->requestAsync($method, $uri, $options);
     }
     try {
         $responses = Promise\unwrap($promises);
         $results = [];
         $counter = 0;
         foreach ($responses as $response) {
             $this->logResponse($transactionIds[$counter], $method, $uris[$counter], $response);
             $results[] = $this->handleResponse($response);
             $counter++;
         }
     } catch (ClientException $e) {
         throw new EWSClientError($e->getCode() . ' error', 0, null, []);
     }
     return $results;
 }
开发者ID:CRUKorg,项目名称:cruk-event-sdk,代码行数:42,代码来源:EWSClient.php

示例3: requestAsync

 public function requestAsync($url, $method = 'GET', $data = [])
 {
     $stack = HandlerStack::create();
     $stack->push(ApiMiddleware::auth());
     $client = new Client(['handler' => $stack]);
     $promise = $client->requestAsync($method, $url, ['headers' => ['Authorization' => 'Bearer ' . $this->token], 'json' => $data, 'content-type' => 'application/json']);
     return $promise;
 }
开发者ID:mergado,项目名称:mergado-api-client-php,代码行数:8,代码来源:HttpClient.php

示例4: __call

 /**
  * @param $method
  * @param $args
  * @return \GuzzleHttp\Promise\PromiseInterface|mixed|\Psr\Http\Message\ResponseInterface
  */
 public function __call($method, $args)
 {
     if (count($args) < 1) {
         throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
     }
     $uri = $args[0];
     $opts = isset($args[1]) ? $args[1] : [];
     return substr($method, -5) === 'Async' ? $this->client->requestAsync(substr($method, 0, -5), $uri, $opts) : $this->client->request($method, $uri, $opts);
 }
开发者ID:bpolaszek,项目名称:httpclientwrapper,代码行数:14,代码来源:HttpClientWrapper.php

示例5: requestAsync

 /**
  * Return a promise for async requests.
  *
  * @param string $method
  * @param string $url
  * @param array  $body
  * @param array  $query
  * @param array  $headers
  *
  * @return \GuzzleHttp\Promise\PromiseInterface
  */
 public function requestAsync($method, $url, $body = [], $query = [], $headers = [])
 {
     if (!empty($body)) {
         $body = encode($body);
         $headers['Content-Type'] = 'application/json';
     } else {
         $body = null;
     }
     $headers = array_merge($this->global_headers, $headers);
     return $this->client->requestAsync($method, $url, ['query' => $query, 'body' => $body, 'headers' => $headers]);
 }
开发者ID:duffleman,项目名称:json-client,代码行数:22,代码来源:JSONClient.php

示例6: requestAsync

 /**
  * Do a HTTP request
  * 
  * @param string $method
  * @param string $uri
  * @param array  $options
  * @return \GuzzleHttp\Promise\PromiseInterface|Response
  */
 public function requestAsync($method, $uri = null, array $options = [])
 {
     if (isset($options['data'])) {
         if (in_array($method, ['GET', 'HEAD', 'OPTIONS'])) {
             $options['query'] = $options['data'];
             unset($options['data']);
         } else {
             $this->applyPostData($options);
         }
     }
     return parent::requestAsync($method, $uri, $options);
 }
开发者ID:jasny,项目名称:db-rest,代码行数:20,代码来源:Client.php

示例7: __call

 /**
  * Pass undefined requests to client
  *
  * @param string $method
  * @param arary  $args
  *
  * @return \GuzzleHttp\Psr7\Response
  */
 public function __call($method, $args)
 {
     $paths = isset($args[0]) ? $args[0] : false;
     $params = isset($args[1]) ? $args[1] : [];
     if (substr($method, -4) === 'Many') {
         $promises = [];
         foreach ($paths as $path) {
             $promises[$path] = $this->client->requestAsync(substr($method, 0, -4), '/' . $path, $params);
         }
         return Promise\unwrap($promises);
     }
     return $this->client->request($method, $paths ? '/' . $paths : null, $params);
 }
开发者ID:rpcjacobs,项目名称:magescan,代码行数:21,代码来源:Request.php

示例8: logout

 public static function logout(UserAuthTicket $authTicket)
 {
     try {
         $authentication = AppAuthenticator::getInstance();
         //var_dump($authTicket);
         $resourceUrl = static::getLogoutUrl($authTicket);
         $client = new Client(['base_uri' => MozuConfig::$baseAppAuthUrl, 'verify' => false]);
         $headers = ["content-type" => "application/json", Headers::X_VOL_APP_CLAIMS => $authentication->getAppClaim()];
         var_dump($headers);
         $promise = $client->requestAsync("DELETE", $resourceUrl, ['headers' => $headers, 'exceptions' => true]);
         $promise->wait();
     } catch (\Exception $e) {
         HttpHelper::checkError($e);
     }
 }
开发者ID:sgorman,项目名称:mozu-php-sdk,代码行数:15,代码来源:UserAuthenticator.php

示例9: refreshAuthTicket

 private function refreshAuthTicket()
 {
     try {
         $requestData = new AuthTicketRequest();
         $requestData->refreshToken = $this->authTicket->refreshToken;
         $client = new Client(['base_uri' => MozuConfig::$baseAppAuthUrl, 'verify' => false]);
         $headers = ["content-type" => "application/json"];
         $body = json_encode($requestData);
         $promise = $client->requestAsync("PUT", AuthTicketUrl::RefreshAppAuthTicketUrl(null)->getUrl(), ['headers' => $headers, 'body' => $body, 'exceptions' => true]);
         $response = $promise->wait();
         $jsonResp = $response->getBody(true);
         $this->authTicket = json_decode($jsonResp);
         $this->setRefreshInterval(true);
     } catch (\Exception $e) {
         HttpHelper::checkError($e);
     }
 }
开发者ID:sgorman,项目名称:mozu-php-sdk,代码行数:17,代码来源:AppAuthenticator.php

示例10: authenticate

 public static function authenticate(CustomerUserAuthInfo $customerAuthInfo, $tenantId, $siteId)
 {
     try {
         $authentication = AppAuthenticator::getInstance();
         $resourceUrl = CustomerAuthTicketUrl::createUserAuthTicketUrl(null);
         $client = new Client(['base_uri' => static::getAuthUrl($tenantId), 'verify' => false]);
         $headers = ["content-type" => "application/json", Headers::X_VOL_APP_CLAIMS => $authentication->getAppClaim(), Headers::X_VOL_SITE => $siteId];
         $body = json_encode($customerAuthInfo);
         $promise = $client->requestAsync($resourceUrl->getVerb(), $resourceUrl->getUrl(), ['headers' => $headers, 'body' => $body, 'exceptions' => true]);
         $response = $promise->wait();
         $jsonResp = $response->getBody(true);
         $authResponse = json_decode($jsonResp);
         $authProfile = static::setUserAuth($authResponse, $tenantId, $siteId);
         return $authProfile;
     } catch (\Exception $e) {
         HttpHelper::checkError($e);
     }
 }
开发者ID:sgorman,项目名称:mozu-php-sdk,代码行数:18,代码来源:CustomerAuthenticator.php

示例11: requestJsons

 /**
  * Create and send an HTTP request and return the decoded JSON response
  * body
  *
  * @throws EWSClientError
  *
  * @param string $method
  *   HTTP method e.g. GET, POST, DELETE
  * @param array $uris
  *   URI strings
  * @param array $options
  *   Request options to apply
  * @return mixed
  *   JSON decoded body from EWS
  */
 public function requestJsons($method, $uris, array $options = [])
 {
     // Add the OAuth access token to the request headers
     $options = array_merge($options, ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken]]);
     $promises = [];
     foreach ($uris as $uri) {
         $promises[] = $this->http->requestAsync($method, $uri, $options);
     }
     try {
         $responses = Promise\unwrap($promises);
         $results = [];
         foreach ($responses as $response) {
             $results[] = $this->handleResponse($response);
         }
     } catch (ClientException $e) {
         throw new EWSClientError($e->getCode() . ' error', 0, null, []);
     }
     return $results;
 }
开发者ID:dgcollard,项目名称:cruk-event-sdk,代码行数:34,代码来源:EWSClient.php

示例12: disconnectOxygenAsync

 /**
  * @param UriInterface $url
  * @param Session      $session
  *
  * @return Promise
  *
  * @resolves bool True if the module was just disconnected, false if it was already disconnected.
  *
  * @rejects  RequestException
  * @rejects  OxygenPageNotFoundException
  */
 public function disconnectOxygenAsync(UriInterface $url, Session $session)
 {
     return $this->client->getAsync($url->withQuery(\GuzzleHttp\Psr7\build_query(['q' => 'admin/config/oxygen/disconnect'])), [RequestOptions::COOKIES => $session->getCookieJar(), RequestOptions::AUTH => $session->getAuthData()])->then(function (ResponseInterface $response) use($url, $session) {
         $crawler = new Crawler((string) $response->getBody(), (string) $url);
         try {
             $form = $crawler->filter('form#oxygen-admin-disconnect')->form();
             if ($form->get('oxygen_connected')->getValue() === 'yes') {
                 return $this->client->requestAsync($form->getMethod(), $form->getUri(), [RequestOptions::COOKIES => $session->getCookieJar(), RequestOptions::AUTH => $session->getAuthData(), RequestOptions::HEADERS => ['referer' => $form->getUri()], RequestOptions::FORM_PARAMS => $form->getPhpValues()]);
             }
             return false;
         } catch (\Exception $e) {
             throw new OxygenPageNotFoundException();
         }
     })->then(function ($result) {
         if (!$result instanceof ResponseInterface) {
             // Module was already disconnected.
             return false;
         }
         // Module was successfully disconnected.
         return true;
     });
 }
开发者ID:Briareos,项目名称:Undine,代码行数:33,代码来源:Client.php

示例13: multiRequest

 /**
  * @inheritdoc
  */
 public function multiRequest(array $urls)
 {
     $client = new Client();
     $promises = array();
     foreach ($urls as $urlName => $urlData) {
         if (is_string($urlData)) {
             $urlData = array($urlData, array());
         }
         $urlOptions = new Options($urlData[1]);
         $method = $urlOptions->get('method', 'GET', 'up');
         $args = $urlOptions->get('args');
         $url = 'GET' === $method ? Url::addArg((array) $args, $urlData[0]) : $urlData[0];
         $promises[$urlName] = $client->requestAsync($method, $url, $this->_getClientOptions($urlOptions, $method, $args));
     }
     $httpResults = Promise\unwrap($promises);
     /** @var string $resName */
     /** @var Response $httpResult */
     $result = array();
     foreach ($httpResults as $resName => $httpResult) {
         $result[$resName] = array($httpResult->getStatusCode(), $httpResult->getHeaders(), $httpResult->getBody()->getContents());
     }
     return $result;
 }
开发者ID:jbzoo,项目名称:http-client,代码行数:26,代码来源:Guzzle6.php

示例14: requestAsync

 public function requestAsync($method, $endpoint, array $data = array())
 {
     $promise = $this->client->requestAsync($method, $this->api_prefix . $endpoint, $this->getRequestOptions($method, $data))->then(function (ResponseInterface $res) {
         return $this->getBody($res);
     }, function (RequestException $e) {
         // See if we can simplify the exception.
         if (!$e->hasResponse()) {
             throw new StockfighterRequestException('', -1, 'No response from server.');
         }
         $this->handleResponseErrors($e->getResponse());
         // Otherwise, throw a general error.
         throw new StockfighterRequestException('', -1, 'Unknown error: ' . $e->getMessage());
     })->then($this->global_fulfilled, $this->global_rejected);
     // Add a timer to the loop to monitor this request.
     $timer = $this->stockfighter->loop->addPeriodicTimer(0, \Closure::bind(function () use(&$timer) {
         $this->tick();
         if (empty($this->handles) && Promise\queue()->isEmpty()) {
             $timer->cancel();
         }
     }, $this->handler, $this->handler));
     // Return the promise.
     return $promise;
 }
开发者ID:sammarks,项目名称:stockfighter-php,代码行数:23,代码来源:DefaultAPICommunicator.php

示例15: requestAsync

 /**
  * @inheritDoc
  */
 public function requestAsync($method, $uri, array $options = [])
 {
     return $this->client->requestAsync($method, $uri, $options);
 }
开发者ID:audiens,项目名称:appnexus-client,代码行数:7,代码来源:Auth.php


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