/** * @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()); }
/** * @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; }
/** * @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()); }
/** * @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; } }
/** * 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); }
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()); }
/** * 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); }
/** * @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; }
/** * @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]; }
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; } } }
/** * @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; }
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); } }
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); }
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); } }
/** * @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()); }
/** * Upsert CSV payload into datastore * * @param string $path * @param string $payload * @return array */ public function update($path, $payload, $mode = 'update') { $options = array('body' => $payload, 'headers' => ['Accept' => 'application/json', 'Content-Type' => 'text/csv', 'X-App-Token' => $this->appToken], 'auth' => [$this->email, $this->password]); $verb = $mode == 'replace' ? 'PUT' : 'POST'; $response = $this->client->request($verb, $path, $options); $response = $response->getBody()->getContents(); return json_decode($response, true); }
/** * @param string $uri * @param string $method * @param array $options * * @return ResponseInterface */ protected function request(string $uri, string $method = 'GET', array $options = []) : ResponseInterface { try { return $this->client->request($method, $uri, array_merge($options, ['http_errors' => false])); } catch (ConnectException $e) { throw new \PHPUnit_Framework_IncompleteTestError('Beware, server is not running'); } }
/** * Execute the console command. * * @return mixed */ public function handle() { foreach (RssFeed::limit(1)->get() as $feed) { $response = $this->client->request('GET', $feed->url); $feed->html = $response->getBody()->getContents(); $feed->save(); } }
/** * @param string $method * @param string $path * @param array $options * * @return array */ private function request($method, $path, $options) { $uri = $this->endpoint . $path; $authOption = ['auth' => [$this->authToken, '']]; $options = array_merge($options, $authOption); $response = $this->httpClient->request($method, $uri, $options); return json_decode($response->getBody(), true); }
/** * @param string $method * @param string $path * @param array $options * @return Response */ public function sendRequest($method, $path, array $options = []) { $url = $this->getUrl() . $path; $options['body'] = array_key_exists('body', $options) ? \GuzzleHttp\Psr7\stream_for(json_encode($options['body'])) : null; $options['headers'] = $this->headers; $guzzleResponse = $this->client->request($method, $url, $options); return new Response($guzzleResponse->getStatusCode(), (string) $guzzleResponse->getBody()); }
/** * Submit the request and build the response object. * * @param string $method * @param string $url * @param array $options * @return \Fungku\HubSpot\Http\Response */ private function makeRequest($method, $url, $options) { try { return new Response($this->client->request($method, $url, $options)); } catch (RequestException $e) { return new Response($e->getResponse()); } }
/** * Send a HTTP GET request * * @param $url * @param array $queryParameters * @return string * @throws TransportException */ public function get($url, array $queryParameters) { try { return (string) $this->client->request('GET', $url, ['query' => $queryParameters])->getBody(); } catch (\RuntimeException $ex) { throw new TransportException($ex->getMessage(), null, $ex); } }
/** * @param string $method * @param string $url * @param array $options * @return mixed */ private function sendRequest($method, $url, array $options = []) { $defaultOptions = ['headers' => ['Authorization' => 'Bearer ' . $this->accessToken, 'X-PrettyPrint' => '1', 'Accept' => 'application/json', 'Accept-Encoding' => 'gzip']]; $requestOptions = array_merge($defaultOptions, $options); $response = $this->client->request($method, $url, $requestOptions); $this->checkResponse($response); return \GuzzleHttp\json_decode($response->getBody()->getContents()); }
public function getZipFromCity($city) { if (empty($city)) { return array('result' => ''); } $response = $this->client->request('POST', 'find/city', ['json' => ['city' => trim($city)]]); return json_decode($response->getBody(), true); }
/** * Display the specified resource. * * @param $link * @return \Illuminate\Http\Response * @internal param int $id */ public function show($link) { $client = new Client(); $baseUrl = 'https://www.youmagine.com/'; $response = $client->get($baseUrl . 'designs/' . $link); $code = $response->getBody(); $xs = Selector::loadHTML($code); // Scrape Youmagine thing information from DOM try { $name = $xs->find('/html/body/div[2]/div/h1')->extract(); $description = $xs->find('//*[@id="information"]/div[2]')->extract(); $files = $xs->findAll('//*[@id="documents"]/div/ul/li[*]/div[3]/div[1]/a')->map(function ($node) { return $node->find('@href')->extract(); }); } catch (NodeNotFoundException $e) { return response()->view('thing.none'); } // Get files $downloadLinks = []; foreach ($files as $file) { $response = $client->get($baseUrl . $file, ['allow_redirects' => false]); $code = $response->getBody(); preg_match('/"(.*?)"/', $code, $downloadLinkMatch); $downloadLinks[] = $downloadLinkMatch[1]; } // Get access token $response = $client->request('POST', 'https://developer.api.autodesk.com/authentication/v1/authenticate', ['form_params' => ['client_id' => env('AUTODESK_CLIENT_ID', ''), 'client_secret' => env('AUTODESK_CLIENT_SECRET', ''), 'grant_type' => 'client_credentials']]); $authToken = json_decode($response->getBody())->access_token; // Create a bucket $bucketKey = Str::lower(Str::random(16)); $response = $client->request('POST', 'https://developer.api.autodesk.com/oss/v2/buckets', ['json' => ['bucketKey' => $bucketKey, 'policyKey' => 'transient'], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); $bucketKey = json_decode($response->getBody())->bucketKey; // Upload to bucket $bucket = []; foreach ($downloadLinks as $downloadLink) { $fileName = pathinfo($downloadLink)['basename']; $file = fopen(base_path('public/cache/' . $fileName), 'w'); /** @noinspection PhpUnusedLocalVariableInspection */ $response = $client->get($downloadLink, ['sink' => $file]); $file = fopen(base_path('public/cache/' . $fileName), 'r'); $response = $client->request('PUT', 'https://developer.api.autodesk.com/oss/v2/buckets/' . $bucketKey . '/objects/' . $fileName, ['body' => $file, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); $body = json_decode($response->getBody()); $bucket[] = ['filename' => $body->objectKey, 'urn' => $body->objectId]; } // Set up references $references = ['master' => $bucket[0]['urn'], 'dependencies' => []]; foreach ($bucket as $file) { if ($file['filename'] === $bucket[0]['filename']) { continue; } $references['dependencies'][] = ['file' => $file['urn'], 'metadata' => ['childPath' => $file['filename'], 'parentPath' => $bucket[0]['filename']]]; } $response = $client->post('https://developer.api.autodesk.com/references/v1/setreference', ['json' => $references, 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); // Register data with the viewing services $urn = base64_encode($bucket[0]['urn']); $response = $client->post('https://developer.api.autodesk.com/viewingservice/v1/register', ['json' => ['urn' => $urn], 'headers' => ['Authorization' => 'Bearer ' . $authToken]]); return response()->view('thing.show', compact('name', 'description', 'urn', 'authToken') + ['pollUrl' => 'https://developer.api.autodesk.com/viewingservice/v1/' . $urn, 'dl' => $downloadLinks[0]]); }
/** * @param ApnsClient $apns * @param Message $message * * @return bool * * @throws ApnsException */ public function __invoke(ApnsClient $apns, Message $message) { try { $response = $this->httpClient->request('POST', $apns->getPushURI($message), ['json' => json_encode($message), 'cert' => $apns->getSslCert(), 'headers' => $message->getMessageHeaders(), 'curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_2_0]]); return 200 === $response->getStatusCode(); } catch (RequestException $e) { throw self::factoryException($e); } }
/** * Send the message via POST * @param array $message the message to post * @return object the HTTP status code. */ public function send(array $message) { // Build message $this->message = $message; // @TODD add switch for sync or async options // Guzzle request, send data to Segment. $response = $this->client->request('POST', $this->endpoint, ['json' => $this->message]); return $response; }
/** * Before outputting custom links, it is validated to ensure that the user is not * directed off to a broken link. If a 404 is detected, it is hidden. * * @param $link The proposed link * * @return bool */ private function linkIsValid($link) { $link = $this->docDomain . $link; try { $resp = $this->client->request('HEAD', $link); } catch (ClientException $e) { } return $resp->getStatusCode() < 400; }
/** * Send a request to the URL. * * Get the body response and convert it to an array. * * @param string $method * @param string $url * @param mixed $data * @return stdClass */ public function send($method, $url, $data = null) { $response = $this->guzzle->request($method, $url, $data); if ($method == 'POST') { return true; } return $this->xmlToArray($response->getBody()); }
public function postUrl(string $url, $params = [], $options = []) { $res = $this->client->request('POST', $url, array_merge($this->defaults, $options, ['form_params' => $params])); if ($res->getStatusCode() === 200) { return (string) $res->getBody(); } return false; }