本文整理汇总了PHP中GuzzleHttp\Client::request方法的典型用法代码示例。如果您正苦于以下问题:PHP Client::request方法的具体用法?PHP Client::request怎么用?PHP Client::request使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GuzzleHttp\Client
的用法示例。
在下文中一共展示了Client::request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: request
/**
* @param Request $request
* @return RawResponse
* @throws \Exception
*/
public function request(Request $request)
{
$res = $this->client->request('GET', $request->getUrl());
if ($res->getStatusCode() == 200) {
return new RawResponse((string) $res->getBody());
}
throw new \Exception('Error code', $res->getStatusCode());
}
示例2: findAll
/**
* @param int $start
* @param int $maxResults
* @return Category[]|null
* @throws RepositoryException
*/
public function findAll($start = 0, $maxResults = 100)
{
$cacheKey = self::CACHE_NAMESPACE . sha1($start . $maxResults);
if ($this->isCacheEnabled()) {
if ($this->cache->contains($cacheKey)) {
return $this->cache->fetch($cacheKey);
}
}
$compiledUrl = $this->baseUrl . "?start_element={$start}&num_elements={$maxResults}";
$response = $this->client->request('GET', $compiledUrl);
$repositoryResponse = RepositoryResponse::fromResponse($response);
if (!$repositoryResponse->isSuccessful()) {
throw RepositoryException::failed($repositoryResponse);
}
$stream = $response->getBody();
$responseContent = json_decode($stream->getContents(), true);
$stream->rewind();
$result = [];
if (!$responseContent['response']['content_categories']) {
$responseContent['response']['content_categories'] = [];
}
foreach ($responseContent['response']['content_categories'] as $segmentArray) {
$result[] = Category::fromArray($segmentArray);
}
if ($this->isCacheEnabled()) {
$this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION);
}
return $result;
}
示例3: sendRequest
/**
* @param \Nomadez\SDK\Request $request
*
* @return \Nomadez\SDK\Response
* @author Andreas Glaser
*/
public function sendRequest(Request $request)
{
$headers = $this->config['headers'];
if ($this->apiKey) {
$headers[$this->config['api.key.header']] = $this->apiKey;
}
$headers = array_replace_recursive($headers, $request->getHeaders());
try {
$data = ['method' => $request->getMethod(), 'url' => $this->config['api.url'] . $request->getUri() . '.json', 'options' => ['headers' => $headers, 'timeout' => $this->config['client.timeout'], 'connect_timeout' => $this->config['client.connect_timeout'], 'allow_redirects' => true, 'body' => null]];
if (!ValueHelper::isEmpty($request->getPayload())) {
$data['options']['body'] = json_encode($request->getPayload());
}
$this->log(LogLevel::DEBUG, $data);
$response = $this->guzzleHttpClient->request($data['method'], $data['url'], $data['options']);
} catch (GuzzleException\ServerException $e) {
$response = $e->getResponse();
} catch (GuzzleException\ClientException $e) {
$response = $e->getResponse();
}
$bodyRaw = $response->getBody()->getContents();
$bodyDecoded = json_decode($bodyRaw);
$log = ['statusCode' => $response->getStatusCode(), 'body' => $bodyDecoded, 'bodyRaw' => $bodyRaw];
$this->log(LogLevel::DEBUG, $log);
return new Response($response->getStatusCode(), $bodyRaw, $response->getHeaders());
}
示例4: getTokenInfo
/**
* @param string $token
*
* @return UserProfileInterface|null
*/
protected function getTokenInfo($token)
{
try {
$response = $this->httpClient->request('GET', 'https://www.googleapis.com/oauth2/v3/tokeninfo', ['query' => ['id_token' => $token]]);
$tokenInfo = json_decode($response->getBody()->getContents(), true);
// check if we can get user identifier
if (empty($tokenInfo) || empty($tokenInfo['sub'])) {
return null;
}
// do not accept tokens generated not for our application even if they are valid,
// to protect against "man in the middle" attack
if ($tokenInfo['aud'] != $this->options['audience']) {
return null;
}
$userProfile = new UserProfile();
$userProfile->setIdentifier($tokenInfo['sub']);
$userProfile->setDisplayName(isset($tokenInfo['name']) ? $tokenInfo['name'] : null);
$userProfile->setFirstName(isset($tokenInfo['given_name']) ? $tokenInfo['given_name'] : null);
$userProfile->setLastName(isset($tokenInfo['family_name']) ? $tokenInfo['family_name'] : null);
$userProfile->setEmail(isset($tokenInfo['email']) ? $tokenInfo['email'] : null);
$userProfile->setEmailVerified(isset($tokenInfo['email_verified']) ? $tokenInfo['email_verified'] : false);
return $userProfile;
} catch (ClientException $e) {
return null;
}
}
示例5: get
/**
* Get Data from Pixabay API
*
* @param array $options
* @param bool $returnObject
* @param bool $resetOptions
* @param string $segment
* @return mixed
*/
public function get(array $options = [], $returnObject = false, $resetOptions = false, $segment = self::SEGMENT_IMAGES)
{
$this->parseOptions($options, $resetOptions);
$response = $this->client->request('GET', self::API_ROOT . $segment, ['query' => $this->options]);
$data = $response->getBody()->getContents();
return json_decode($data, $returnObject);
}
示例6: call
public function call($interface, $method, $version, $httpMethod, $parameters)
{
$path = implode('/', array($interface, $method, 'v' . $version));
$parameters['key'] = $this->_apiKey;
$response = $this->_guzzleClient->request($httpMethod, $path, array('query' => $parameters));
return json_decode($response->getBody()->getContents());
}
示例7: request
/**
* Makes a request to a URL.
*
* @param string $uri
* @param array $params
* @param string $method
*
* @return \Psr7\Request
*/
protected function request($uri, array $params = [], $method = 'post')
{
$endpoint = $this->config->get('centurian.endpoint');
$uri = sprintf('%s/%s', $endpoint, $uri);
$data = ['form_params' => $params, 'auth' => [$this->config->get('centurian.token'), null]];
return $this->client->request($method, $uri, $data);
}
示例8: fetchHtmlBody
/**
* @param $victim
* @param $useProxy
* @param bool $useCache
* @return string
*/
public function fetchHtmlBody($victim, $useProxy, $useCache, $proxyId = 0, $html = '')
{
$filePath = $this->serviceManager->getLocalTmpFolder();
if ($useCache) {
$html = $this->getCachedData($filePath, $victim->getName());
if (empty($html)) {
$html = 'No cached data!';
}
} else {
error_log('ID: ' . $proxyId . "\n", 3, '/tmp/logger');
$client = new GuzzleHttp\Client();
if (!isset($this->proxies[$proxyId])) {
$html = 'None of proxies worked!';
} else {
try {
if ($useProxy) {
$res = $client->request('GET', $victim->getUrl(), ['proxy' => $this->proxies[$proxyId], 'User-Agent' => 'Mozilla/5.0', 'connect_timeout' => $this->timeout]);
} else {
$res = $client->request('GET', $victim->getUrl());
}
$html = $res->getBody()->getContents();
$this->setCachedData($filePath . '/' . $victim->getName(), $html);
} catch (\Exception $re) {
$html = '<h1>FAILED!</h1>' . $re->getMessage();
$proxyId++;
$this->fetchHtmlBody($victim, $useProxy, $useCache, $proxyId, $html);
}
}
}
error_log("=============================\n\n\n\n\n", 3, '/tmp/logger');
return $html;
}
示例9: getCSRFToken
/**
* @return string
*/
private function getCSRFToken()
{
$response = $this->httpClient->request('GET', $this->modemOptions['url'] . $this->modemOptions['login_form'], array('headers' => array('User-Agent' => $this->modemOptions['user_agent'], 'Connection' => 'keep-alive'), 'cookies' => $this->cookieJar));
$loginFormHtml = $response->getBody()->getContents();
preg_match('#name="CSRFValue" value=(\\d+)>#', $loginFormHtml, $matches);
return $matches[1];
}
示例10: subscribe
public function subscribe($email, $newsletter)
{
$checksum = md5($email);
$url = sprintf('https://us7.api.mailchimp.com/3.0/lists/%s/members/%s', $newsletter, $checksum);
$client = new Client();
try {
$response = $client->request('GET', $url, ['auth' => ['anystring', $this->api_key]]);
switch ($response->getStatusCode()) {
case 200:
// update user, set status to subscribed
$response = $client->request('PATCH', $url, ['auth' => ['anystring', $this->api_key], 'json' => ['status' => 'subscribed']]);
return true;
break;
}
} catch (RequestException $e) {
switch ($e->getResponse()->getStatusCode()) {
case 404:
// no subscriber found, subscribe now
$response = $client->request('POST', sprintf('https://us7.api.mailchimp.com/3.0/lists/%s/members', $newsletter), ['auth' => ['anystring', $this->api_key], 'json' => ['email_address' => $email, 'status' => 'subscribed']]);
return true;
break;
default:
return false;
}
}
}
示例11: makeRequest
/**
* @param string $uri URI or ENDPOINT (see constants)
* @param array $formParams
*
* @return array|bool
*/
protected function makeRequest($uri, $formParams = [])
{
$uri = empty($this->getEndpointUriBySlug($uri)) ? $uri : $this->getEndpointUriBySlug($uri);
$requestMethod = self::REQUEST_METHOD_GET;
$isAuthRequest = isset($formParams[self::AUTH_PARAM_USERNAME], $formParams[self::AUTH_PARAM_PASSWORD]);
if (!$isAuthRequest && empty($this->token)) {
$this->addError('Can\'t work with API without token. Log in first.');
return false;
}
$requestData = ['headers' => ['Authorization' => 'Token ' . $this->token]];
if ($isAuthRequest) {
$requestMethod = self::REQUEST_METHOD_POST;
$requestData = ['form_params' => $formParams];
}
try {
$guzzleResponse = $this->guzzleClient->request($requestMethod, $uri, $requestData);
} catch (ClientException $e) {
$this->addError($e->getMessage());
return false;
}
if (self::RESPONSE_CODE_SUCCESS !== $guzzleResponse->getStatusCode()) {
$this->addError('Failed to make a request to ' . $uri . '. ' . $this->getDetailedGuzzleErrorMessage($guzzleResponse));
return false;
}
$guzzleData = json_decode($guzzleResponse->getBody(), true);
if ($isAuthRequest) {
if (!isset($guzzleData['token']) || empty($guzzleData['token'])) {
$this->addError('Failed to find a token.');
return false;
}
$this->token = (string) $guzzleData['token'];
return true;
}
return isset($guzzleData['results']) ? (array) $guzzleData['results'] : $guzzleData;
}
示例12: retreiveData
protected function retreiveData($url, $format = self::FORMAT_PLAIN, $postData = false)
{
try {
if (array_key_exists('proxy', $this->config) && $this->config['proxy'] !== false) {
$client = new Client(['proxy' => $this->config['proxy']]);
} else {
$client = new Client();
}
if ($postData) {
$response = $client->request('POST', $url, ['form_params' => $postData]);
} else {
$response = $client->request('GET', $url);
}
if ($response->getStatusCode() == 200) {
switch ($format) {
case DataUpstream::FORMAT_JSON:
return json_decode($response->getBody());
case DataUpstream::FORMAT_XML:
return simplexml_load_string($response->getBody());
default:
return $response->getBody();
}
} else {
throw new Exception('Source returned code ' . $response->getStatusCode());
}
} catch (Exception $e) {
throw new GushException($e->getMessage(), GushException::Data);
}
}
示例13: send
private function send($endpoint, array $data)
{
$this->validate($endpoint, $data);
$result = $this->client->request('POST', $this->endpoints[$endpoint]['url'], ['form_params' => $data]);
//var_dump( $result);
return new W2AResponse($result);
}
示例14: retreiveData
protected function retreiveData($url, $format = self::FORMAT_PLAIN, $postData = false)
{
try {
if (array_key_exists('proxy', $this->config) && $this->config['proxy'] !== false) {
$client = new Client(['proxy' => $this->config['proxy']]);
} else {
$client = new Client();
}
$options = ['timeout' => 30, 'headers' => ['User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36']];
if ($postData) {
$options['form_params'] = $postData;
$response = $client->request('POST', $url, $options);
} else {
$response = $client->request('GET', $url, $options);
}
if ($response->getStatusCode() == 200) {
switch ($format) {
case DataUpstream::FORMAT_JSON:
return json_decode($response->getBody());
case DataUpstream::FORMAT_XML:
return simplexml_load_string($response->getBody());
default:
return $response->getBody();
}
} else {
throw new Exception('Source returned code ' . $response->getStatusCode());
}
} catch (Exception $e) {
throw new GushException($e->getMessage(), GushException::Data);
}
}
示例15: request
/**
* @param string $method
* @param string$uri
* @param array $queryParams
* @param array $requestParams
* @param array $options
* @param bool $secured
*
* @return array|stdClass
* @throws GuzzleException
* @throws Exception
*/
public function request($method, $uri, array $queryParams, array $requestParams, array $options, $secured)
{
$this->eventDispatcher->dispatch(BeforeClientRequestEvent::NAME, new BeforeClientRequestEvent($method, $uri, $queryParams, $requestParams, $options, $secured));
$originalRequest = ['method' => $method, 'uri' => $uri, 'queryParams' => $queryParams, 'requestParams' => $requestParams, 'option' => $options, 'secured' => $secured];
//Check for on behalf of in order to inject it if needed
$isOnBehalfOfUsedInParams = false;
foreach ([&$queryParams, &$requestParams] as &$paramsArray) {
if (array_key_exists('on_behalf_of', $paramsArray)) {
//isset is not used because id skips null-s
if (null !== $paramsArray['on_behalf_of']) {
$this->session->setOnBehalfOf($paramsArray['on_behalf_of']);
$isOnBehalfOfUsedInParams = true;
} else {
$onBehalfOf = $this->session->getOnBehalfOf();
if (null !== $onBehalfOf) {
$paramsArray['on_behalf_of'] = $onBehalfOf;
}
}
}
}
try {
//Wrap whole section if someone, for example, throws exceptions for PHP warnings etc.
if ($secured) {
//Perhaps check here if auth token set?
$options['headers']['X-Auth-Token'] = $this->session->getAuthToken();
}
$queryParams = array_filter($queryParams);
$requestParams = array_filter($requestParams);
if (count($requestParams) > 0) {
if (!isset($options['form_params'])) {
$options['form_params'] = [];
}
$options['form_params'] = array_merge($options['form_params'], $requestParams);
}
//Force no-exceptions in order to provide descriptive error messages
$options['http_errors'] = false;
$url = $this->applyApiBaseUrl($uri, $queryParams);
$response = $this->client->request($method, $url, $options);
switch ($response->getStatusCode()) {
case 200:
$data = json_decode($response->getBody()->getContents());
return $data;
default:
//Everything that's not 200 consider error and dispatch event
$event = new ClientHttpErrorEvent($response, $requestParams, $method, $url, $originalRequest);
$this->eventDispatcher->dispatch(ClientHttpErrorEvent::NAME, $event);
$interceptedResponse = $event->getInterceptedResponse();
if (null !== $interceptedResponse) {
return $interceptedResponse;
}
}
} finally {
//If on-behalf-of was injected through params, clear it now
if ($isOnBehalfOfUsedInParams) {
$this->session->clearOnBehalfOf();
}
}
throw new Exception($response->getBody()->getContents());
}