當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。