本文整理汇总了PHP中GuzzleHttp\Client类的典型用法代码示例。如果您正苦于以下问题:PHP Client类的具体用法?PHP Client怎么用?PHP Client使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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();
}
示例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();
}
示例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;
}
示例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)];
}
}
示例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('/');
}
示例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;
}
示例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());
}
示例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());
}
}
示例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;
}
示例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());
}
示例12: getStubbedHttpClient
private function getStubbedHttpClient($responses = [])
{
$client = new HttpClient();
$mockSubscriber = new SubscriberMock($responses);
$client->getEmitter()->attach($mockSubscriber);
return $client;
}
示例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;
}
示例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;
}
示例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();
}