本文整理汇总了PHP中GuzzleHttp\Client类的典型用法代码示例。如果您正苦于以下问题:PHP Client类的具体用法?PHP Client怎么用?PHP Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: getClientWithBody
protected function getClientWithBody($body)
{
$client = new Client();
$mock = new Mock([new Response(200, [], Stream::factory($body))]);
$client->getEmitter()->attach($mock);
return $client;
}
开发者ID:bogdaan,项目名称:distance,代码行数:7,代码来源:HttpProviderTestBase.php
示例2: handle
public function handle()
{
$this->totalPageCount = count($this->users);
$client = new Client();
$requests = function ($total) use($client) {
foreach ($this->users as $key => $user) {
$uri = 'https://api.github.com/users/' . $user;
(yield function () use($client, $uri) {
return $client->getAsync($uri);
});
}
};
$pool = new Pool($client, $requests($this->totalPageCount), ['concurrency' => $this->concurrency, 'fulfilled' => function ($response, $index) {
$res = json_decode($response->getBody()->getContents());
$this->info("请求第 {$index} 个请求,用户 " . $this->users[$index] . " 的 Github ID 为:" . $res->id);
$this->countedAndCheckEnded();
}, 'rejected' => function ($reason, $index) {
$this->error("rejected");
$this->error("rejected reason: " . $reason);
$this->countedAndCheckEnded();
}]);
// 开始发送请求
$promise = $pool->promise();
$promise->wait();
}
开发者ID:qloog,项目名称:laravel5-backend,代码行数:25,代码来源:MultithreadingRequest.php
示例3: execute
/**
* Execute the command.
*
* @param \Symfony\Component\Console\Input\InputInterface $input
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @return void
*/
public function execute(InputInterface $input, OutputInterface $output)
{
$client = new Client();
$modname = $input->getArgument('modname');
$modversion = $input->getArgument('modversion');
$config = solder_config();
$response = $client->get($config->api);
$server = $response->json();
$response = $client->get($config->api . '/mod/' . $modname . '/' . $modversion);
$json = $response->json();
if (isset($json['error'])) {
throw new \Exception($json['error']);
}
$rows = array();
foreach ($json as $key => $value) {
if ($key == 'versions') {
$rows[] = array("<info>{$key}</info>", implode($value, "\n"));
} else {
$rows[] = array("<info>{$key}</info>", mb_strimwidth($value, 0, 80, "..."));
}
}
$output->writeln('<comment>Server:</comment>');
$output->writeln(" <info>{$server['api']}</info> version {$server['version']}");
$output->writeln(" {$api}");
$output->writeln('');
$output->writeln("<comment>Mod:</comment>");
$table = new Table($output);
$table->setRows($rows)->setStyle('compact')->render();
}
开发者ID:indemnity83,项目名称:mcmod,代码行数:36,代码来源:ModCommand.php
示例4: send
/**
* Send the notification
*/
public function send()
{
$Client = new Client();
$failures = array();
$result = array();
$data = ["registration_ids" => [], "data" => ["title" => $this->data['subject'], "message" => $this->data['body']]];
foreach ($this->data['recipients'] as $user_id => $userdata) {
$ThisUser = UserFactory::CreateUser($user_id);
$subscriptions = Notifications::getPushSubscriptions($ThisUser);
foreach ($subscriptions as $sub) {
$data['registration_ids'][] = $sub['registration_id'];
}
}
if (empty($data['registration_ids'])) {
return;
}
try {
$response = $Client->post($sub['endpoint'], ["headers" => ["Content-Type" => "application/json", "Authorization" => "key=" . GOOGLE_SERVER_KEY], "json" => $data]);
$body = $response->getBody();
$result = json_decode($body, true);
$this->removeStaleSubscriptions($result, $data['registration_ids']);
$return = array("stat" => true, "failures" => $result);
} catch (RequestException $e) {
$return = ["stat" => false, "failures" => ["message" => $e->getMessage(), "body" => $e->getRequest()->getBody()]];
}
return $return;
}
开发者ID:railpage,项目名称:railpagecore,代码行数:30,代码来源:Push.php
示例5: run
public function run()
{
if (Yii::$app->getRequest()->isPost) {
Yii::$app->getRequest()->parsers = ['application/json' => 'yii\\web\\JsonParser'];
$user_class = Satellizer::getComponent()->identityClass;
$params = ['code' => Yii::$app->getRequest()->getBodyParam('code'), 'client_id' => Yii::$app->getRequest()->getBodyParam('clientId'), 'redirect_uri' => Yii::$app->getRequest()->getBodyParam('redirectUri'), 'client_secret' => Satellizer::getComponent()->facebook['clientSecret']];
$cliente = new Client();
$accessToken = $cliente->get(Satellizer::getComponent()->facebook['accessTokenUrl'], ['query' => $params])->json();
$profile = $cliente->get(Satellizer::getComponent()->facebook['graphApiUrl'], ['query' => $accessToken])->json();
if (Yii::$app->getRequest()->getHeaders()->get('Authorization')) {
$user = $user_class::findOne(['facebook' => $profile['id']]);
if ($user) {
throw new \yii\web\ConflictHttpException('There is already a Facebook account that belongs to you', 409);
}
$token = explode(' ', Yii::$app->getRequest()->getHeaders()->getHeaders()->get('Authorization'))[1];
$payload = (array) Satellizer::getComponent()->decodeToken($token);
$user = $user_class::find($payload['sub']);
$this->facebook = $profile['id'];
$user->save();
$user->facebookLink($profile);
} else {
$user = $user_class::findOne(['facebook' => $profile['id']]);
if ($user) {
return ['token' => Satellizer::getComponent()->createToken($user)];
}
$user = Yii::createObject($user_class);
$this->facebook = $profile['id'];
$user->save();
$user->facebookLink($profile);
}
return ['token' => Satellizer::getComponent()->createToken($user)];
}
}
开发者ID:wfcreations,项目名称:yii2-satellizer-server,代码行数:33,代码来源:FacebookAction.php
示例6: login
/**
* Soundcloud login callback.
*/
public function login(Request $request)
{
// Check if we have code query.
if (!$request->has('code')) {
// If not, redirect to homepage.
return redirect('/');
}
// Parse returned code.
$code = $request->get('code');
// Use Guzzle to form request.
$client = new Client();
// Get access_token.
$response = $client->request('POST', 'https://api.soundcloud.com/oauth2/token', ['form_params' => ['code' => $code, 'client_id' => env('SOUNDCLOUD_CLIENT_ID'), 'client_secret' => env('SOUNDCLOUD_CLIENT_SECRET'), 'redirect_uri' => env('SOUNDCLOUD_CALLBACK_URL'), 'grant_type' => 'authorization_code']]);
// Redirect to homepage if response status is not 200.
if ($response->getStatusCode() != 200) {
return redirect('/');
}
// Parse access_token.
$response = json_decode($response->getBody()->getContents());
$access_token = $response->access_token;
//Init GoogleRepository after authentication when we have access_token.
$this->initSoundcloudRepository($request, $access_token);
$this->saveSession($request, $access_token);
return redirect('/');
}
开发者ID:ritey,项目名称:audious,代码行数:28,代码来源:SoundcloudController.php
示例7: getUrls
private function getUrls($url)
{
$httpClient = new Client();
$content = $httpClient->get(new Uri($url));
$config = json_decode($content->getBody());
$projects = array();
foreach ($config as $configElement) {
$urls = array();
$pageKey = $configElement->system->name;
$url = $configElement->system->url;
$urls[$pageKey]["url"] = $url;
$urls[$pageKey]["project"] = $configElement->system->project;
$requests = array();
foreach ($configElement->collections as $collection) {
$requests[$collection->name] = array();
foreach ($collection->requests as $collectionRequest) {
$requests[$collection->name][] = $collectionRequest->pattern;
}
}
$urls[$pageKey]['requests'] = $requests;
if (!array_key_exists($configElement->system->project->identifier, $projects)) {
$projects[$configElement->system->project->identifier] = array();
}
if (!array_key_exists('urls', $projects[$configElement->system->project->identifier])) {
$projects[$configElement->system->project->identifier]['urls'] = [];
}
$projects[$configElement->system->project->identifier]['project'] = $configElement->system->project;
$projects[$configElement->system->project->identifier]['urls'] = array_merge($urls, $projects[$configElement->system->project->identifier]['urls']);
}
return $projects;
}
开发者ID:sebastianneubert,项目名称:MissingRequest,代码行数:31,代码来源:KoalamonCommand.php
示例8: testNonExistent
/**
* Tests non-existent drug to ensure http response code passed correctly.
*/
public function testNonExistent()
{
$client = new Client();
$request = $client->get('http://web/v1/fda/RAINBOWS', ['http_errors' => false]);
$response = $request;
$this->assertEquals(404, $response->getStatusCode());
}
开发者ID:ethanteague,项目名称:nebula,代码行数:10,代码来源:FDAAPITest.php
示例9: postMo
public function postMo(array $messageArr)
{
try {
$this->msgCounter++;
$words = explode(' ', $messageArr['text']);
$moParams = array_merge($this->config['mo'], $messageArr, array('message_id' => $this->msgCounter, 'keyword' => $words[0] . '@' . $messageArr['short_id']));
echo "Posting params from MO to client @" . $messageArr['url'] . ': ' . json_encode($moParams) . "\n";
$response = $this->httpClient->post($messageArr['url'], ['body' => $moParams]);
if ($response->getStatusCode() != 200) {
echo 'received MO reply with status code: ' . $response->getStatusCode() . ', and body' . $response->getBody() . "\n";
return $this->sendError($response->getBody());
}
$responseBody = $response->getBody();
echo 'received MO reply:' . $responseBody . "\n";
$this->broadcast('mo_reply', array('message' => $this->parseXMLResponse($responseBody)));
} catch (\GuzzleHttp\Exception\RequestException $requestException) {
echo 'received MO reply error of class [' . get_class($requestException) . '] and message: ' . $requestException->getMessage() . "\n";
if ($requestException->hasResponse()) {
echo "\nbody: " . $requestException->getResponse()->getBody() . "\n";
echo "\ncode: " . $requestException->getResponse()->getStatusCode() . "\n";
$this->sendError($requestException->getMessage(), $this->parseXMLResponse($requestException->getResponse()->getBody()));
}
$this->sendError($requestException->getMessage());
} catch (\Exception $exc) {
echo 'received MO reply error of class [' . get_class($exc) . '] and message: ' . $exc->getMessage() . "\n";
$this->sendError($exc->getMessage());
}
}
开发者ID:rukavina,项目名称:sms-inbound-mock,代码行数:28,代码来源:PremiumMockApp.php
示例10: send
public function send()
{
if (!$this->validate()) {
throw new SMSMessageException('Could not send message');
}
if (empty($this->strId)) {
$objUuid = Uuid::uuid4();
$this->strId = $objUuid->toString();
}
$arrParams = ['cc' => $this->strUsername, 'ekey' => $this->strPassword, 'message' => $this->strBody, 'title' => $this->strSenderId, 'network' => $this->strNetwork, 'value' => $this->fltValue, 'currency' => $this->strCurrency, 'encoding' => $this->strEncoding, 'number' => $this->strMsisdn, 'id' => $this->strId, 'reply' => $this->intReply];
if ($this->blBinary) {
$arrParams['binary'] = (int) $this->blBinary;
$arrParams['udh'] = $this->strUdh;
}
if (!empty($this->shortcode)) {
$arrParams['shortcode'] = $this->shortcode;
}
$this->objLogger->addDebug('Sending the following to txtNation:', $arrParams);
$objClient = new Client(['base_uri' => 'http://client.txtnation.com/', 'timeout' => 10.0]);
$objResponse = $objClient->get('/gateway.php', [RequestOptions::QUERY => $arrParams, RequestOptions::SYNCHRONOUS => true, RequestOptions::ALLOW_REDIRECTS => true, RequestOptions::HEADERS => ['User-agent' => 'txtNationGatewayLibraryPHP/1.0'], RequestOptions::HTTP_ERRORS => false]);
$objResult = new SMSMessageResult($objResponse);
$objResult->setCallbackId($this->strId);
if (!$objResult->success()) {
$this->objLogger->addAlert('Message was not sent. ', ['error' => $objResult->getErrorMessage()]);
}
return $objResult;
}
开发者ID:saleemepoch,项目名称:txtnation,代码行数:27,代码来源:Request.php
示例11: send
/**
* @param \DonePM\ConsoleClient\Http\Commands\Command $command
*
* @return mixed|\Psr\Http\Message\ResponseInterface
*/
public function send(Command $command)
{
if ($command instanceof NeedsToken) {
$command->token($this->token);
}
return $this->client->send($command->request());
}
开发者ID:donepm,项目名称:cli-client,代码行数:12,代码来源:Client.php
示例12: getStubbedHttpClient
private function getStubbedHttpClient($responses = [])
{
$client = new HttpClient();
$mockSubscriber = new SubscriberMock($responses);
$client->getEmitter()->attach($mockSubscriber);
return $client;
}
开发者ID:PacoFigueroa,项目名称:loginlaravel,代码行数:7,代码来源:OAuth2ProviderTest.php
示例13: factory
/**
* @param array $options
* @param JobBuilderInterface|null $jobBuilder
* @return FileConversionClient
*/
public static function factory($options = array(), JobBuilderInterface $jobBuilder = null)
{
// $requiredOptions = array(
// 'application_id',
// );
//
// foreach ($requiredOptions as $optionName) {
// if (!isset($options[$optionName]) || $options[$optionName] === '') {
// throw new Exception\InvalidArgumentException(
// sprintf('Missing required configuration option "%s"', $optionName)
// );
// }
// }
$defaultOptions = array('base_url' => 'https://dws-fileconversion.detailnet.ch/api', 'defaults' => array('connect_timeout' => 10, 'timeout' => 60));
$headers = array('Accept' => 'application/json', 'User-Agent' => 'dfw-fileconversion/' . self::CLIENT_VERSION);
if (isset($options[self::OPTION_APP_ID])) {
$headers[self::HEADER_APP_ID] = $options[self::OPTION_APP_ID];
}
if (isset($options[self::OPTION_APP_KEY])) {
$headers[self::HEADER_APP_KEY] = $options[self::OPTION_APP_KEY];
}
// These are always applied
$overrideOptions = array('defaults' => array('exceptions' => false, 'headers' => $headers));
// Apply options
$config = array_replace_recursive($defaultOptions, $options, $overrideOptions);
$httpClient = new HttpClient($config);
$httpClient->getEmitter()->attach(new Subscriber\Http\ProcessError());
$description = new ServiceDescription(require __DIR__ . '/ServiceDescription/FileConversion.php');
$client = new static($httpClient, $description, $jobBuilder);
return $client;
}
开发者ID:detailnet,项目名称:dfw-fileconversion,代码行数:36,代码来源:FileConversionClient.php
示例14: factory
public static function factory($options = array())
{
// $requiredOptions = array();
//
// foreach ($requiredOptions as $optionName) {
// if (!isset($options[$optionName]) || $options[$optionName] === '') {
// throw new Exception\InvalidArgumentException(
// sprintf('Missing required configuration option "%s"', $optionName)
// );
// }
// }
// These are applied if not otherwise specified
$defaultOptions = array('base_url' => self::getDefaultServiceUrl(), 'defaults' => array('connect_timeout' => 10, 'timeout' => 60));
$headers = array('Accept' => 'application/json', 'User-Agent' => 'denner-client/' . self::CLIENT_VERSION);
if (isset($options[self::OPTION_APP_ID])) {
$headers[self::HEADER_APP_ID] = $options[self::OPTION_APP_ID];
}
if (isset($options[self::OPTION_APP_KEY])) {
$headers[self::HEADER_APP_KEY] = $options[self::OPTION_APP_KEY];
}
// These are always applied
$overrideOptions = array('defaults' => array('exceptions' => false, 'headers' => $headers));
// Apply options
$config = array_replace_recursive($defaultOptions, $options, $overrideOptions);
$httpClient = new HttpClient($config);
$httpClient->getEmitter()->attach(new Subscriber\Http\ProcessError());
$serviceDescriptionFile = __DIR__ . sprintf('/ServiceDescription/%s.php', self::getServiceDescriptionName());
if (!file_exists($serviceDescriptionFile)) {
throw new Exception\RuntimeException(sprintf('Service description does not exist at "%s"', $serviceDescriptionFile));
}
$description = new ServiceDescription(require $serviceDescriptionFile);
$client = new static($httpClient, $description);
return $client;
}
开发者ID:detailnet,项目名称:denner-client,代码行数:34,代码来源:DennerClient.php
示例15: handle
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$client = new Client();
$end_point = 'http://api.serviceu.com/rest/events/occurrences?orgKey=b96cd642-acbb-4eb7-95a2-f18c0f01d5b1&format=json';
$response = $client->get($end_point);
$data = json_decode($response->getBody(true));
$active_records = [];
CalendarEvent::unguard();
foreach ($data as $event) {
array_push($active_records, $event->OccurrenceId);
$record = CalendarEvent::withPast()->where('id', '=', $event->OccurrenceId)->first() ?: new CalendarEvent();
$record->{'id'} = $event->OccurrenceId;
$record->{'event_number'} = $event->EventId;
$record->{'title'} = $event->Name;
$record->{'starts_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceStartTime);
$record->{'ends_at'} = Carbon::createFromFormat('m/d/Y h:i:s A', $event->OccurrenceEndTime);
$record->{'location'} = $event->LocationName;
$record->{'address'} = $event->LocationAddress;
$record->{'address2'} = $event->LocationAddress2;
$record->{'city'} = $event->LocationCity;
$record->{'state'} = $event->LocationState;
$record->{'zip'} = $event->LocationZip;
$record->{'description'} = $event->Description;
$record->{'contact'} = $event->ContactName;
$record->{'contact_email'} = $event->ContactEmail;
$record->{'contact_phone'} = $event->ContactPhone;
$record->{'department'} = $event->DepartmentName;
$record->save();
}
CalendarEvent::reguard();
// Remove non-existing events
CalendarEvent::withPast()->whereNotIn('id', $active_records)->delete();
// Purge old events
CalendarEvent::where('ends_at', '<', Carbon::now()->subMonth(2))->delete();
}
开发者ID:mcculley1108,项目名称:faithpromise.org,代码行数:40,代码来源:ImportEvents.php
示例16: download
protected function download()
{
$this->output->writeln(sprintf("\n Downloading %s...\n", $this->projectName));
$distill = new Distill();
$componentFile = $distill->getChooser()->setStrategy(new MinimumSize())->addFile($this->remoteFileUrl)->getPreferredFile();
$downloadCallback = function ($expected, $total, $client, $request, $response) {
// Don't initialize the progress bar for redirects as the size is much smaller
if ($response->getStatusCode() >= 300) {
return;
}
printf(" Download: %d %% \r", 100 * ($total / $expected));
};
$client = new Client();
$client->getEmitter()->attach(new Progress(null, $downloadCallback));
// store the file in a temporary hidden directory with a random name
$this->downloadedFilePath = getcwd() . DIRECTORY_SEPARATOR . '.' . uniqid(time()) . DIRECTORY_SEPARATOR . $this->projectName . '.' . ltrim(strstr($componentFile, '.'), '.');
//pathinfo($symfonyArchiveFile, PATHINFO_EXTENSION);
try {
$response = $client->get($componentFile);
} catch (ClientException $e) {
throw new \RuntimeException(sprintf("There was an error downloading %s from server:\n%s", $this->getDownloadedFileName(), $e->getMessage()));
}
$this->fs->dumpFile($this->downloadedFilePath, $response->getBody());
$this->output->writeln("\n");
return $this;
}
开发者ID:mozanturhan,项目名称:droidphp-installer,代码行数:26,代码来源:DownloadCommand.php
示例17: request
/**
* Guzzle 4 Request method implementation
*
* @param string $httpMethod
* @param string $path
* @param array $params
* @param null $version
* @param bool $isAuthorization
*
* @return Response|mixed
* @throws ClientException
* @throws AuthorizeException
* @throws ServerException
* @throws Error
*/
public function request($httpMethod = 'GET', $path = '', $params = array(), $version = null, $isAuthorization = false)
{
$guzzleClient = new GuzzleClient();
switch ($httpMethod) {
case 'GET':
$request = $guzzleClient->createRequest($httpMethod, $path, array('query' => $params));
break;
default:
$request = $guzzleClient->createRequest($httpMethod, $path, array('body' => $params));
}
try {
$res = $guzzleClient->send($request);
} catch (GuzzleException\ClientException $e) {
//catch error 404
$error_message = $e->getResponse();
if ($isAuthorization) {
throw new AuthorizeException($error_message, $e->getCode(), $e->getPrevious());
} else {
throw new ClientException($error_message, $e->getCode(), $e->getPrevious());
}
} catch (GuzzleException\ServerException $e) {
throw new ServerException($e, $e->getCode(), $e->getPrevious());
} catch (GuzzleException\BadResponseException $e) {
throw new Error($e->getResponse(), $e->getCode(), $e->getPrevious());
}
$response = new Response($res->json(), $res->getCode());
return $response;
}
开发者ID:siliconstraits,项目名称:cems-php-sdk,代码行数:43,代码来源:Guzzle4.php
示例18: handle
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->has('token')) {
return response()->json(config('status.messages.404'), 404);
}
$token = $request->input('token');
//Check for API Authentication
$authUrl = config('app.auth');
$client = new Client(['base_url' => $authUrl['base_url']]);
//ToDo : Header or Auth Type need to change later according to Main App Authentication
$headers = ['X-API-KEY' => env('AUTH_APP_KEY'), 'X-API-SECRET' => env('AUTH_APP_SECRET')];
try {
$response = $client->get($authUrl['uri'] . '/' . $token, ['headers' => $headers]);
} catch (ClientException $e) {
$response = $e->getResponse();
}
switch ($response->getStatusCode()) {
case 401:
return response()->json(config('status.messages.401'), 401);
break;
case 200:
$request->session()->put('request_user', $response->json());
return $next($request);
break;
}
return response()->json(config('status.messages.401'), 401);
}
开发者ID:GreenHackers,项目名称:router-app,代码行数:34,代码来源:AuthMiddleware.php
示例19: runRequest
/**
* Runs http calls.
*
* @param string $method
* @param string $url
* @param array $content
* @param boolean $auth
* @return object
*/
public static function runRequest($method, $url, $content, $auth)
{
$guzzle = new GuzzleClient(['http_errors' => false, 'allow_redirects' => true]);
$url = self::$base_url . "/{$url}";
$headers = ['User-Agent' => self::getUserAgent(), 'Content-Type' => 'application/json'];
if (!$auth) {
$headers['authorization'] = DISCORD_TOKEN;
}
$done = false;
$finalRes = null;
while (!$done) {
$content = is_null($content) ? null : json_encode($content);
$request = new Request($method, $url, $headers, $content);
$response = $guzzle->send($request);
// Rate limiting
if ($response->getStatusCode() == 429) {
$tts = $response->getHeader('Retry-After') * 1000;
usleep($tts);
continue;
}
// Not good!
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 226) {
self::handleError($response->getStatusCode(), $response->getReasonPhrase());
continue;
}
$done = true;
$finalRes = $response;
}
return json_decode($finalRes->getBody());
}
开发者ID:jamiebatch452,项目名称:DiscordPHP,代码行数:39,代码来源:Guzzle.php
示例20: fetch
/**
* Make API Call
* @param string $path API Path
* @param array $query Additional query parameters (optional)
* @return GuzzleHttp\Response
*/
public function fetch($path, array $query = [])
{
if (!$this->api instanceof Http) {
$this->setupHttpClient();
}
return $this->api->get($path, ['query' => $query])->json();
}
开发者ID:adamgoose,项目名称:gitlab,代码行数:13,代码来源:Client.php
注:本文中的GuzzleHttp\Client类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论