本文整理汇总了PHP中Guzzle\Http\Client类的典型用法代码示例。如果您正苦于以下问题:PHP Client类的具体用法?PHP Client怎么用?PHP Client使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: connect
public function connect($appKey, $appSecret, $accessToken, $tokenSecret)
{
try {
$client = new Client(self::BASE_URL . '/{version}', ['version' => '1.1']);
$oauth = new OauthPlugin(['consumer_key' => $appKey, 'consumer_secret' => $appSecret, 'token' => $accessToken, 'token_secret' => $tokenSecret]);
return $client->addSubscriber($oauth);
} catch (ClientErrorResponseException $e) {
$req = $e->getRequest();
$resp = $e->getResponse();
print_r($resp);
die('1');
} catch (ServerErrorResponseException $e) {
$req = $e->getRequest();
$resp = $e->getResponse();
die('2');
} catch (BadResponseException $e) {
$req = $e->getRequest();
$resp = $e->getResponse();
print_r($resp);
die('3');
} catch (Exception $e) {
echo 'AGH!';
die('4');
}
}
示例2: setLaundryState
public function setLaundryState(&$laundryPlace)
{
$user = 'youruser';
$pass = 'yourpassword';
try {
$client = new Client($laundryPlace['url']);
$request = $client->get('/LaundryState', [], ['auth' => [$user, $pass, 'Digest'], 'timeout' => 1.5, 'connect_timeout' => 1.5]);
$response = $request->send();
$body = $response->getBody();
libxml_use_internal_errors(true);
$crawler = new Crawler();
$crawler->addContent($body);
foreach ($crawler->filter('img') as $img) {
$resource = $img->getAttribute('src');
$img->setAttribute('src', 'http://129.241.126.11/' . trim($resource, '/'));
}
$crawler->addHtmlContent('<h1>foobar</h1>');
//'<link href="http://129.241.126.11/pic/public_n.css" type="text/css">');
$laundryPlace['html'] = $crawler->html();
libxml_use_internal_errors(false);
preg_match_all('/bgColor=Green/', $body, $greenMatches);
preg_match_all('/bgColor=Red/', $body, $redMatches);
$laundryPlace['busy'] = count($redMatches[0]);
$laundryPlace['available'] = count($greenMatches[0]);
} catch (\Exception $e) {
$laundryPlace['available'] = self::NETWORK_ERROR;
$laundryPlace['busy'] = self::NETWORK_ERROR;
$laundryPlace['html'] = self::NETWORK_ERROR;
}
}
示例3: injectScript
/**
* Injects the livereload script.
*
* @param Response $response A Response instance
*/
protected function injectScript(Response $response)
{
if (function_exists('mb_stripos')) {
$posrFunction = 'mb_strripos';
$substrFunction = 'mb_substr';
} else {
$posrFunction = 'strripos';
$substrFunction = 'substr';
}
$content = $response->getContent();
$pos = $posrFunction($content, '</body>');
if (false !== $pos) {
$script = "livereload.js";
if ($this->checkServerPresence) {
// GET is required, as livereload apparently does not support HEAD requests ...
$request = $this->httpClient->get($script);
try {
$checkResponse = $this->httpClient->send($request);
if ($checkResponse->getStatusCode() !== 200) {
return;
}
} catch (CurlException $e) {
// If error is connection failed, we assume the server is not running
if ($e->getCurlHandle()->getErrorNo() === 7) {
return;
}
throw $e;
}
}
$content = $substrFunction($content, 0, $pos) . "\n" . '<script src="' . $this->httpClient->getBaseUrl() . $script . '"></script>' . "\n" . $substrFunction($content, $pos);
$response->setContent($content);
}
}
示例4: request
/**
* Guzzle3 Request 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)
{
//TODO: Implement Guzzle 3 here
$guzzleClient = new GuzzleClient();
switch ($httpMethod) {
case 'GET':
//TODO: array liked param need manual parser
$request = $guzzleClient->get($path, array(), array('query' => $params));
break;
default:
//default:'Content-Type'=>'application/json' for "*.json" URI
$json_body = json_encode($params);
$request = $guzzleClient->createRequest($httpMethod, $path, array(), $json_body);
$request->setHeader('Content-Type', 'application/json');
}
try {
$res = $request->send();
} catch (GuzzleException\ClientErrorResponseException $e) {
//catch error 404
$error_message = $e->getResponse();
if ($isAuthorization) {
throw new AuthorizeException($error_message, $error_message->getStatusCode(), $e->getPrevious());
} else {
throw new ClientException($error_message, $e->getResponse()->getStatusCode(), $e->getPrevious());
}
} catch (GuzzleException\ServerErrorResponseException $e) {
throw new ServerException($e, '$e->getResponse()->getStatusCode()', $e->getPrevious());
} catch (GuzzleException\BadResponseException $e) {
throw new Error($e->getResponse(), $e->getResponse()->getStatusCode(), $e->getPrevious());
}
$response = new Response($res->json(), $res->getStatusCode());
return $response;
}
示例5: getFileCache
public static function getFileCache($location, $expire = false)
{
if (is_bool($expire)) {
$expire = 60 * 30;
}
$hash = sha1($location);
$cacheDir = self::$cache_url;
$file = "{$cacheDir}{$hash}";
if (file_exists($file)) {
$file_content = file_get_contents($file);
$unserialize_file = unserialize($file_content);
$file_expire = $unserialize_file['expire'];
if ($file_expire > time()) {
return base64_decode($unserialize_file['content']);
}
}
mt_srand();
$randomize_user_agent = self::$user_agents[mt_rand(0, count(self::$user_agents) - 1)];
$location = parse_url($location);
$http = "http://{$location['host']}";
$path = "{$location['path']}?{$location['query']}";
$client = new Client($http);
$request = $client->get($path);
$request->setHeader('User-Agent', $randomize_user_agent);
$response = $request->send();
if (!$response->isSuccessful()) {
return false;
}
$content = $response->getBody(true);
$store = array('date' => time(), 'expire' => time() + $expire, 'content' => base64_encode($content));
$serialize = serialize($store);
file_put_contents($file, $serialize);
return $content;
}
示例6: makeRequest
/**
* Makes the request to the server.
*
* @param string $server
* @param string $service The rest service to access e.g. /connections/communities/all
* @param string $method GET, POST or PUT
* @param string $body
* @param string $headers
*/
public function makeRequest($server, $service, $method, $options, $body = null, $headers = null, $endpointName = "connections")
{
$store = SBTCredentialStore::getInstance();
$settings = new SBTSettings();
$token = $store->getToken($endpointName);
$response = null;
$client = new Client($server);
$client->setDefaultOption('verify', false);
// If global username and password is set, then use it; otherwise use user-specific credentials
if ($settings->getBasicAuthMethod($endpointName) == 'global') {
$user = $settings->getBasicAuthUsername($endpointName);
$password = $settings->getBasicAuthPassword($endpointName);
} else {
$user = $store->getBasicAuthUsername($endpointName);
$password = $store->getBasicAuthPassword($endpointName);
}
try {
$request = $client->createRequest($method, $service, $headers, $body, $options);
if ($settings->forceSSLTrust($endpointName)) {
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
}
if ($method == 'POST' && isset($_FILES['file']['tmp_name'])) {
$request->addPostFile('file', $_FILES['file']['tmp_name']);
}
$request->setAuth($user, $password);
$response = $request->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
$response = $e->getResponse();
}
return $response;
}
示例7: authenticate
public function authenticate(array $credentials)
{
$mcrypt = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($mcrypt), MCRYPT_DEV_RANDOM);
mcrypt_generic_init($mcrypt, $this->cryptPassword, $iv);
$url = $this->getUrl($credentials[self::USERNAME], $credentials[self::PASSWORD], $mcrypt, $iv);
try {
$res = $this->httpClient->get($url)->send();
} catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
if ($e->getResponse()->getStatusCode() === 403) {
throw new \Nette\Security\AuthenticationException("User '{$credentials[self::USERNAME]}' not found.", self::INVALID_CREDENTIAL);
} elseif ($e->getResponse()->getStatusCode() === 404) {
throw new \Nette\Security\AuthenticationException("Invalid password.", self::IDENTITY_NOT_FOUND);
} else {
throw $e;
}
}
$responseBody = trim(mdecrypt_generic($mcrypt, $res->getBody(TRUE)));
$apiData = Json::decode($responseBody);
$user = $this->db->table('users')->where('id = ?', $apiData->id)->fetch();
$registered = new \DateTimeImmutable($apiData->registered->date, new \DateTimeZone($apiData->registered->timezone));
$userData = array('username' => $credentials[self::USERNAME], 'password' => $this->calculateAddonsPortalPasswordHash($credentials[self::PASSWORD]), 'email' => $apiData->email, 'realname' => $apiData->realname, 'url' => $apiData->url, 'signature' => $apiData->signature, 'language' => $apiData->language, 'num_posts' => $apiData->num_posts, 'apiToken' => $apiData->apiToken, 'registered' => $registered->getTimestamp());
if (!$user) {
$userData['id'] = $apiData->id;
$userData['group_id'] = 4;
$this->db->table('users')->insert($userData);
$user = $this->db->table('users')->where('username = ?', $credentials[self::USERNAME])->fetch();
} else {
$user->update($userData);
}
return $this->createIdentity($user);
}
示例8: __construct
/**
* Build a new FactoryDriver
*
* @param Container $app
*/
public function __construct(Container $app)
{
$this->app = $app;
$this->client = new \Guzzle\Http\Client();
$cookiePlugin = new CookiePlugin(new ArrayCookieJar());
$this->client->addSubscriber($cookiePlugin);
}
示例9: create
public static function create($host, $ssl, $clientID, $apiKey)
{
$guzzle = new GuzzleHttpClient(($ssl ? 'https' : 'http') . '://' . $host . '/');
$signer = new RequestSigner($clientID, $apiKey);
$guzzle->addSubscriber($signer);
return new static($guzzle);
}
示例10: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Updating the WSDL file');
$client = $this->getContainer()->get('phpforce.soap_client');
// Get current session id
$loginResult = $client->getLoginResult();
$sessionId = $loginResult->getSessionId();
$instance = $loginResult->getServerInstance();
$url = sprintf('https://%s.salesforce.com', $instance);
$guzzle = new Client($url, array('curl.CURLOPT_SSL_VERIFYHOST' => false, 'curl.CURLOPT_SSL_VERIFYPEER' => false));
// type=* for enterprise WSDL
$request = $guzzle->get('/soap/wsdl.jsp?type=*');
$request->addCookie('sid', $sessionId);
$response = $request->send();
$wsdl = $response->getBody();
$wsdlFile = $this->getContainer()->getParameter('phpforce.soap_client.wsdl');
// Write WSDL
file_put_contents($wsdlFile, $wsdl);
// Run clear cache command
if (!$input->getOption('no-cache-clear')) {
$command = $this->getApplication()->find('cache:clear');
$arguments = array('command' => 'cache:clear');
$input = new ArrayInput($arguments);
$command->run($input, $output);
}
}
示例11: setUp
protected function setUp()
{
$this->httpClient = new HttpClient('http://localhost');
$this->clientMocker = new MockPlugin();
$this->httpClient->addSubscriber($this->clientMocker);
$this->engineClient = new EngineClient($this->httpClient, array('collection_name' => 'widgets'));
}
示例12: connect
public function connect($errors = 0)
{
$client = new Client(null);
if (!file_exists($this->_cookieFile)) {
file_put_contents($this->_cookieFile, "");
}
$cookiePlugin = new CookiePlugin(new FileCookieJar($this->_cookieFile));
$client->addSubscriber($cookiePlugin);
$client->setUserAgent('User-Agent', 'Mozilla/5.0 (Linux; U; Android 4.2.2; de-de; GT-I9195 Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30');
$this->_client = $client;
try {
$url = $this->getLoginUrl();
$this->loginAndGetCode($url);
$this->enterAnswer();
$this->gatewayMe();
$this->auth();
$this->getSid();
$this->utasRefreshNucId();
$this->auth();
$this->utasAuth();
$this->utasQuestion();
} catch (\Exception $e) {
throw $e;
// server down, gotta retry
if ($errors < static::RETRY_ON_SERVER_DOWN && preg_match("/service unavailable/mi", $e->getMessage())) {
$this->connect(++$errors);
} else {
throw new \Exception('Could not connect to the mobile endpoint.');
}
}
return array("nucleusId" => $this->nucId, "userAccounts" => $this->accounts, "sessionId" => $this->sid, "phishingToken" => $this->phishingToken, "platform" => $this->_loginDetails['platform']);
}
示例13: getResponse
/**
* Get RealFaviconGenerator response
*
* @param QueryData $queryData RealFaviconGenerator query
* @return mixed RealFaviconGenerator response
*/
protected function getResponse(QueryData $queryData)
{
$client = new Client($this->generator->getBaseurl());
$request = $client->post($this->generator->getUri(), null, $queryData->__toString());
$response = $client->send($request);
return $response;
}
示例14: testResponse
/**
* @dataProvider cbProvider
*/
public function testResponse($expectedStatusCode, $expectedResponseContent, $request, $testCase, $testHeaders)
{
$process = new Process('php -S [::1]:8999', __DIR__ . '/../../resources');
$process->start();
sleep(1);
$signature = sha1($request . ServerMock::PROJECT_SECRET_KEY);
$headers = null;
if ($testHeaders) {
$headers = $testHeaders;
} else {
$headers = array('Authorization' => 'Signature ' . $signature);
}
$request = $this->guzzleClient->post('/webhook_server.php?test_case=' . $testCase, $headers, $request);
try {
$response = $request->send();
} catch (BadResponseException $e) {
$process->stop();
$response = $e->getResponse();
}
static::assertSame($expectedResponseContent, $response->getBody(true));
static::assertSame($expectedStatusCode, $response->getStatusCode());
static::assertArrayHasKey('x-xsolla-sdk', $response->getHeaders());
static::assertSame(Version::getVersion(), (string) $response->getHeader('x-xsolla-sdk'));
static::assertArrayHasKey('content-type', $response->getHeaders());
if (204 === $response->getStatusCode()) {
static::assertStringStartsWith('text/plain', (string) $response->getHeader('content-type'));
} else {
static::assertStringStartsWith('application/json', (string) $response->getHeader('content-type'));
}
}
示例15: testCollaboratorExists
/**
* Test is beberlei collaborator of doctrine/cache
*/
public function testCollaboratorExists()
{
$client = new Client('https://api.github.com');
$request = $client->get('/repos/doctrine/cache/collaborators/beberlei');
$response = $request->send();
$this->assertEquals($response->getStatusCode(), 204);
}