/** * 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); } }
public function getStatusFromWoeid($woeid) { $request = $this->guzzle->createRequest(self::WEBSERVICE_METHOD, self::WEBSERVICE_URI . $woeid); $response = $this->guzzle->send($request); $status = $this->parseWeatherResponse($response->xml()); return $status; }
/** * Returns a response for specified HTTP request. * * @param Request $request HTTP Request to send. * * @return Response Response for specified request. */ public function send(Request $request) { try { $response = $this->client->send($request); } catch (BadResponseException $e) { $response = $e->getResponse(); } return new Response($response->getStatusCode(), $response->getHeaders(), $response->getBody()); }
/** * @When I send a GET request to :path */ public function iSendAGetRequestTo($path) { $request = $this->guzzleClient->get('http://localhost:8081' . $path); try { $this->lastResponse = $this->guzzleClient->send($request); } catch (GuzzleResponseException $guzzleResponseException) { $this->lastResponse = $guzzleResponseException->getResponse(); } }
/** * @param $spaceId * @param array $attributes * @return array|\Guzzle\Http\Message\Response|null */ public function getContentEntryBy($spaceId, $contentType, $attributes = []) { $path = sprintf(self::CONTENTFUL_ENTRIES_URL . "&content_type=%s", $spaceId, $this->accessToken, $contentType); foreach ($attributes as $attr => $value) { $path .= sprintf("&%s=%s", $attr, $value); } $request = $this->guzzleClient->get($path, [self::CONTENTFUL_HEADERS_V1_JSON]); $response = $this->guzzleClient->send($request); return $response; }
/** * @param string $url * @param array $headers * @param array $options * * @return array|null * @throws \Exception */ public function processQuery($url, $headers = array(), $options = array()) { $request = $this->client->get($url, $headers, $options); /**@var Response */ $response = $this->client->send($request); if ($response->isSuccessful()) { try { return $response->json(); } catch (RuntimeException $cannotParseJsonException) { return $response->getBody(true); } } else { throw new \Exception("Fail to complete the request. Server returns code {$response->getStatusCode()}"); } }
/** * 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; }
/** * Use guzzle to make request to API * * @param Request $request * @return string */ protected function makeHttpRequest($request) { $url = $this->urlBuilder->build($request); $guzzleRequest = $this->guzzle->createRequest('GET', $url); $guzzleResponse = $this->guzzle->send($guzzleRequest); return $guzzleResponse->getBody(); }
public function __construct($token) { $client = new Client(); $request = new Request('POST', self::API_BASE_URL . 'rtm.start?' . http_build_query(['token' => $token]), ['Content-Type' => 'application/x-www-form-urlencoded']); $response = $client->send($request); var_dump(json_decode($response->getBody(true))); }
protected function execute(InputInterface $input, OutputInterface $output) { if ($input->hasOption('input-file') && $input->getOption('input-file')) { $commentFilePath = $input->getOption('input-file'); if (!file_exists($commentFilePath)) { throw new \Exception("{$commentFilePath} not found"); } $commentText = file_get_contents($commentFilePath); } else { if ($input->hasOption('string') && $input->getOption('string')) { $commentText = $input->getOption('string'); } } if (!$commentText) { throw new \Exception('No comment input, add a comment text with -s or -i options'); } $client = new Client(); $request = $client->createRequest('GET', 'https://www.pivotaltracker.com/services/v5/me', array('X-TrackerToken' => 'be17fcf368af9fa35cfe88b7460d2c67')); $response = $client->send($request); $this->projects = array_map(function ($item) { return $item['project_id']; }, json_decode($response->getBody(), true)['projects']); $labelsList = implode(',', $this->projects); $extractor = new StoriesExtractor(); $storyIds = $extractor->collect(); $storyCount = count($storyIds); $output->writeln("Adding comments on {$storyCount} stories on projects {$labelsList}"); foreach ($storyIds as $storyId) { foreach ($this->projects as $project) { $request = $client->createRequest('POST', "https://www.pivotaltracker.com/services/v5/projects/{$project}/stories/{$storyId}/comments"); $request->setHeader('X-TrackerToken', 'be17fcf368af9fa35cfe88b7460d2c67'); $request->setHeader('Content-type', 'application/json'); $request->setHeader('Accept', 'application/json'); $request->setBody(json_encode(['text' => $commentText])); try { $client->send($request); $output->write('.'); break; } catch (ClientErrorResponseException $ex) { $output->writeln('Could not comment on story ' . $storyId); $output->writeln($ex->getResponse()->getBody(true), true); } } } $output->writeln(''); }
/** * {@inheritDoc} */ public function performRequest($url, $parameters, $httpMethod = 'GET') { $request = $this->createRequest($url, $parameters, $httpMethod); try { $response = $this->client->send($request); return $response; } catch (\Imgur\Exception\LogicException $e) { error_log($e->getMessage()); } catch (\Imgur\Exception\RuntimeException $e) { error_log($e->getMessage()); } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) { $responseData = $e->getResponse()->json(); error_log('Request to: ' . $responseData['data']['request'] . ' failed with: [' . $responseData['status'] . ']"' . $responseData['data']['error'] . '"'); } catch (Exception $e) { error_log($e->getMessage()); } return false; }
function it_sends_requests(HttpClient $http, UniqushRequest $uniqushRequest, RequestInterface $request, EntityBodyInterface $responseBody) { $uniqushRequest->getUrl()->willReturn('/push'); $uniqushRequest->getQuery()->willReturn($query = ['service' => 'test', 'subscriber' => 'foo', 'msg' => 'bar']); $http->post('/push', [], $query)->shouldBeCalled()->willReturn($request); $http->send($request)->shouldBeCalled()->willReturn($responseBody); $responseBody->__toString()->willReturn('OK'); $this->send($uniqushRequest)->shouldReturn('OK'); }
/** * Call Guzzle Post request method * * @param array $data Address data * @param string $verb Method to be called - should only be geocode for now * @return Guzzle\Http\Message\Response */ protected function bulkPost($data, $fields, $verb = 'geocode') { $url = self::BASE_URL . $verb . "?fields=" . implode(',', $fields) . "&api_key=" . $this->apiKey; $headers = ['Content-Type' => 'application/json']; $payload = json_encode($data); $request = $this->client->post($url, $headers, $payload, []); $response = $this->client->send($request); return $this->checkResponse($response); }
protected function execute(InputInterface $input, OutputInterface $output) { $label = $input->getArgument('label'); $extractor = new StoriesExtractor(); $storyIds = $extractor->collect(); $client = new Client(); $request = $client->createRequest('GET', 'https://www.pivotaltracker.com/services/v5/me', array('X-TrackerToken' => 'be17fcf368af9fa35cfe88b7460d2c67')); $response = $client->send($request); $this->projects = array_map(function ($item) { return $item['project_id']; }, json_decode($response->getBody(), true)['projects']); $labelsList = implode(',', $this->projects); $storyCount = count($storyIds); $output->writeln("Labeling {$storyCount} stories on projects {$labelsList}"); foreach ($storyIds as $storyId) { foreach ($this->projects as $project) { $request = $client->createRequest('GET', "https://www.pivotaltracker.com/services/v5/projects/{$project}/stories/{$storyId}", ['X-TrackerToken' => 'be17fcf368af9fa35cfe88b7460d2c67']); // $request->setHeader§('X-TrackerToken', 'be17fcf368af9fa35cfe88b7460d2c67'); try { $storyData = $client->send($request); } catch (ClientErrorResponseException $ex) { continue; } $body = $storyData->getBody(true); $storyData = json_decode($body, true); $labels = $storyData['labels']; $labels[] = ['name' => $label]; $request = $client->createRequest('PUT', "https://www.pivotaltracker.com/services/v5/projects/{$project}/stories/{$storyId}"); $request->setHeader('X-TrackerToken', 'be17fcf368af9fa35cfe88b7460d2c67'); $request->setHeader('Content-type', 'application/json'); $request->setHeader('Accept', 'application/json'); $request->setBody(json_encode(['labels' => $labels])); try { $client->send($request); $output->write('.'); break; } catch (ClientErrorResponseException $ex) { $output->writeln('Could not label story ' . $storyId); $output->writeln($ex->getResponse()->getBody(true), true); } } } $output->writeln(''); }
/** * @param GuzzleRequest $request * @return GuzzleRequest */ private function processRequest(GuzzleRequest $request) { try { $response = $this->client->send($request); } catch (TransferException $e) { $json_exception = $e->getResponse()->json(); HipChat::throwException($json_exception['error']['code'], $json_exception['error']['message'], $request->getUrl()); } return $response; }
/** * @return string */ public function send($xml, Port $port, BindingOperation $bindingOperation) { $url = $port->getDomElement()->evaluate("string(soap:address/@location)", array("soap" => SoapClient::NS)); $soapAction = $bindingOperation->getDomElement()->evaluate("string(soap:operation/@soapAction)", array("soap" => SoapClient::NS)); $request = new EntityEnclosingRequest("POST", $url); $request->setBody($xml, "text/xml; charset=utf-8"); $request->addHeader("SOAPAction", '"' . $soapAction . '"'); if ($this->debugUri) { $request->setUrl($this->debugUri); } try { $response = $this->client->send($request); } catch (BadResponseException $e) { $response = $e->getResponse(); } if (!$response->isSuccessful() && strpos($response->getContentType(), '/xml') === false) { throw new TransportException($response->getReasonPhrase(), $response->getStatusCode()); } return $response->getBody(true); }
/** * @return array|\Guzzle\Http\Message\Response|null */ private function performCall(HttpClient $httpClient) { try { return $httpClient->send($this->request); } catch (RequestException $e) { $response = $e->getResponse(); if (null === $response) { throw $e; } return $response; } }
private function getEndpoint($token) { $client = new Client(); $request = new Request('POST', 'https://slack.com/api/rtm.start?' . http_build_query(['token' => $token]), ['Content-Type' => 'application/x-www-form-urlencoded']); $this->emitter->emit('log', ['Requesting RTM start']); $response = $client->send($request); $responseData = json_decode($response->getBody(true)); $this->emitter->emit('log', ['RTM started']); $this->selfId = $responseData->self->id; $this->emitter->emit('log', ['My ID is: ' . $this->selfId]); return $responseData->url; }
public function doManyRequests(array $requests, array $headers = array()) { $totalToDo = count($requests); $responses = array(); try { while ($totalToDo > 0) { $clientRequests = array(); for ($i = 0; $i < $this->parallelLimit && $totalToDo > 0; $i++, $totalToDo--) { $clientRequests[] = $this->client->post('', $headers, json_encode(array_shift($requests))); } $responses = array_merge($responses, $this->client->send($clientRequests)); } } catch (\Exception $e) { throw new Exception('Error in request : ' . $e->getMessage()); } $results = array(); foreach ($responses as $k => $response) { $results[$k] = $this->parseResponse($response); } return $results; }
/** * @param ReportDefinition[] $report_definitions * * @return array * @throws \Exception */ public function downloadReports($report_definitions) { $responses = array(); $offset = 0; do { list($sliced_report_definitions_count, $requests) = $this->getNextRequests($report_definitions, $offset); // if $requests is none, wait a moment to free some slots and try again if (count($requests) == 0) { usleep(10000); continue; } try { $responses = array_merge($responses, $this->client->send($requests)); } catch (MultiTransferException $e) { $this->freeUsedRequestCount($sliced_report_definitions_count); $messages = ''; foreach ($e as $exception) { /** @noinspection PhpUndefinedMethodInspection */ $element = new \SimpleXMLElement($exception->getResponse()->getBody('true')); $api_error = $element->ApiError->type; $trigger = $element->ApiError->trigger; $messages .= $api_error . ' : ' . $trigger . "\n"; } throw new \Exception($messages); } $this->freeUsedRequestCount($sliced_report_definitions_count); } while (count($responses) < count($report_definitions)); $reports = array(); /** @var Response[] $responses */ foreach ($responses as $response) { $response_body = $response->getBody(true); $xml = gzdecode($response_body); $report = $this->xml_parser->reportXmlToArray($xml); $reports[] = $report; } $this->fixFieldTypes($reports, $report_definitions); return $reports; }
/** * @param Request $request * * @return array|mixed */ public function callAPI(Request $request) { try { $client = new Client($this->getEndpoint()); $request = $this->beforeSend($request); $method = $request->getMethod(); $params = $request->getParameters(); $mergedResponse = null; $currentPage = 1; $totalPages = 1; while ($totalPages >= $currentPage) { $apiRequest = $client->createRequest($method, $request->getUrl(), $request->getHeaders(), $request->getBody(), array()); // Enable pagination if ($method === 'GET') { $params['page'] = $currentPage; } // Assign parameters $query = $apiRequest->getQuery(); foreach ($params as $key => $value) { $query->set($key, $value); } // Since Guzzle automatically overwrites a new header when the request // is POST / PATCH / DELETE / PUT, we need to overwrite the Content-Type header // with setBody() function. if ($method !== 'GET') { $apiRequest->setBody(json_encode($request->getBody()), 'application/json'); } $response = $client->send($apiRequest)->json(); if (json_last_error() !== JSON_ERROR_NONE) { throw new BadResponseException('Error decoding client API JSON', $response); } if (!$this->responseOk($response)) { $this->logAPICall($this->getAPIClientName(), array('type' => 'response', 'body' => $response), true); } if (isset($response['result_info'])) { $totalPages = $response['result_info']['total_pages']; $mergedResponse = $this->mergeResponses($mergedResponse, $response); } else { $mergedResponse = $response; } $currentPage += 1; } return $mergedResponse; } catch (BadResponseException $e) { $errorMessage = $this->getErrorMessage($e); $this->logAPICall($this->getAPIClientName(), array('type' => 'request', 'method' => $request->getMethod(), 'path' => $request->getUrl(), 'headers' => $request->getHeaders(), 'params' => $request->getParameters(), 'body' => $request->getBody()), true); $this->logAPICall($this->getAPIClientName(), array('type' => 'response', 'reason' => $e->getResponse()->getReasonPhrase(), 'code' => $e->getResponse()->getStatusCode(), 'body' => $errorMessage, 'stacktrace' => $e->getTraceAsString()), true); return $this->createAPIError($errorMessage); } }
/** * @param string $repository * @param string $format * * @return \PUGX\Badge\Model\Badge */ public function createComposerLockBadge($repository, $format = 'svg') { $repo = str_replace('.git', '', $this->packageRepository->fetchByRepository($repository)->getOriginalObject()->getRepository()); $request = $this->client->head($repo . '/blob/master/composer.lock', array(), array('timeout' => 2, 'connect_timeout' => 1, 'exceptions' => false)); $response = $this->client->send($request); $status = 500; if ($request) { $status = $response->getStatusCode(); } $this->text = self::LOCK_ERROR; $color = self::COLOR_ERROR; $subject = self::SUBJECT_ERROR; if (200 === $status) { $this->text = self::LOCK_COMMITTED; $color = self::COLOR_COMMITTED; $subject = self::SUBJECT; } elseif (404 === $status) { $this->text = self::LOCK_UNCOMMITTED; $color = self::COLOR_UNCOMMITTED; $subject = self::SUBJECT; } return $this->createBadgeFromRepository($repository, $subject, $color, $format); }
/** * Patch (partial update) an object at a set location ($path) * @param string $path the path to post this object to. * @param object $object the object to be posted to given path * @param array $headers an array of headers to send with the request * @return \DrestClient\Response $response Response object with a populated representation instance * @throws ErrorException upon the return of any error document from the server */ public function patch($path, &$object, array $headers = array()) { $representation = $this->getRepresentationInstance(); $representation->update($object); $request = $this->transport->patch($path, $headers, $representation->__toString()); foreach ($this->getVarsFromPath($path) as $key => $value) { $request->setPostField($key, $value); } $request->setHeader('Content-Type', $representation->getContentType()); try { $response = $this->transport->send($request); } catch (BadResponseException $exception) { throw $this->handleErrorResponse($exception); } return new Response($representation, $response); }
/** * @param string $repo * @param string $branch * @return Response */ protected function getQueueLocation($repo, $branch) { $header = $this->getCrumbHeader(); $post = new EntityEnclosingRequest('POST', $this->buildUrl, [$header]); $post->setAuth($this->username, $this->passkey)->setPath('/job/' . $repo . '/buildWithParameters/api/xml')->setPostField('BUILD_TYPE', $branch); try { return $this->httpClient->send($post); } catch (ClientErrorResponseException $e) { $response = $e->getResponse(); switch ($response->getStatusCode()) { case 404: throw new \InvalidArgumentException("Repository '{$repo}' not found"); default: throw new $e(); } } }
/** * @param $method * @param $url * @param array|null $payload * @return array|Response|null */ protected function doRequest($method, $url, array $payload = null) { if ($this->apiConfiguration->getEnabled()) { if ($payload) { $payload = ['payload' => json_encode($payload)]; } $url = 'http://' . $this->apiConfiguration->getApiHostname() . $url; $factory = new Factory(); $requestSigner = $factory->newRequestSigner(); $credentials = new Credentials($this->apiConfiguration->getKey(), $this->apiConfiguration->getSecret()); $guzzle = new Client(); $request = $guzzle->createRequest($method, $url, ['content-type' => 'application/json'], $payload); $requestSigner->signRequest(new GuzzleRequestAdapter($request), $credentials); $response = $guzzle->send($request); return $response; } return null; }
/** * @param Guzzle\Http\Message\RequestInterface $request * @return Guzzle\Http\Message\Response|null * @throws Exception\AccessTokenException * @throws \Exception */ private function sendRequest(Guzzle\Http\Message\RequestInterface $request) { // Clean the query string of any null valued parameters $request->getQuery()->replace(array_filter($request->getQuery()->toArray())); try { return $this->guzzleClient->send($request); } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { switch ($e->getResponse()->getStatusCode()) { case 401: throw new Exception\AccessTokenException(); break; default: $hydrator = new Hydrator\ErrorHydrator(); $error = $hydrator->hydrate($e->getResponse()->json(), new Entity\Error()); throw new Exception\SpotifyException($error); break; } } }
/** * Send the request */ public function send() { // make a request object $this->request = $this->client->createRequest($this->method, $this->host . $this->resource); // set headers foreach ($this->headers as $header => $value) { $this->request->setHeader($header, $value); } // set body if (!empty($this->body)) { $this->request->setBody($this->body); } try { // finally send the request $this->response = $this->client->send($this->request); } catch (BadResponseException $e) { $this->response = $this->request->getResponse(); } $this->sent = true; }
/** * Get a Klout\Model\User by their Klout ID. * * @param String $kloutId * @param Boolean $fullData * @throws InvalidArgumentException * @throws ResourceNotFoundException * @return \Klout\Model\User */ public function getUser($kloutId, $fullData = true) { $this->assertValidUserIdForNetwork(self::NETWORK_KLOUT, $kloutId); try { // Get the data for the user $requests = array($this->client->get('user.json/' . $kloutId)); if ($fullData) { $requests[] = $this->client->get('user.json/' . $kloutId . '/influence'); $requests[] = $this->client->get('user.json/' . $kloutId . '/topics'); } $responses = $this->client->send($requests); } catch (HttpRequestException $e) { // If there are partial responses then the method // will return those responses $responses = $this->handleHttpRequestException($e); } $influenceData = array(); $topicsData = array(); $userData = array(); /* @var $response Response */ foreach ($responses as $response) { if (stripos($response->getEffectiveUrl(), '/influence') !== false) { $influenceData = $response->json(); } elseif (stripos($response->getEffectiveUrl(), '/topics') !== false) { $topicsData = $response->json(); } else { $userData = $response->json(); } } if (empty($userData)) { throw new ResourceNotFoundException('Could not find the user information for Klout user ID: ' . $kloutId); } $user = new User(); $user->populate($userData, $influenceData, $topicsData); $identity = new Identity(); $identity->setKloutId($kloutId); $identity->setNetworkName(self::NETWORK_KLOUT); $identity->setNetworkUserId($kloutId); $user->addIdentity($identity); return $user; }
/** * @param RequestInterface $request * * @param string $className If you omit this parameter you will get Response object * @param DeserializationContext $context * * @return FacilitiesResponse|Facility|Address|AddressesResponse|DoctorsResponse|Doctor|DoctorServicesResponse|ServicesResponse|BookingsResponse|BookVisitResponse|PutSlotsResponse|SlotsResponse|Response * @throws \Exception */ private function authorizedRequest(RequestInterface $request, $className = null, DeserializationContext $context = null) { /** @var FacilitiesResponse|Facility|Address|AddressesResponse|DoctorsResponse|Doctor|DoctorServicesResponse|ServicesResponse|BookingsResponse|BookVisitResponse|PutSlotsResponse|SlotsResponse $object */ /** @var Error $error */ $object = null; $response = null; $error = null; if ($this->isAuthorized() === false) { $error = (new Error())->setCode(403)->setMessage('Token is neither valid nor authorized'); } try { $response = $this->client->send($request); } catch (BadResponseException $e) { /* * You may want to tolerate 40x errors, * For example: * - If parameters can't be validated you will receive 400 * - If there isn't any item to show, you will receive 404 * - If you try to access unauthorized doctor or facility or address you will receive 403 */ $response = $e->getResponse(); $statusCode = $response->getStatusCode(); $error = $this->serializer->deserialize($response->getBody(true), Error::class, 'json'); $error->setCode($statusCode); } //We don't know expected return type so just return raw response. if ($className === null) { return $response; } //If there was an error, instantiate the expected class and set the actual Error object; //If not then we should simply return the expected class instance with data. if ($error === null) { $object = $this->serializer->deserialize($response->getBody(true), $className, 'json', $context); } else { $object = new $className(); $object->setError($error); } return $object; }
/** * @covers Guzzle\Http\Curl\CurlMulti * @covers Guzzle\Http\Curl\CurlMulti::removeErroredRequest * @expectedException Guzzle\Common\Exception\ExceptionCollection * @expectedExceptionMessage Thrown before sending! */ public function testCatchesExceptionsBeforeSendingRequests() { $client = new Client($this->getServer()->getUrl()); $request = $client->get(); $request->getEventDispatcher()->addListener('request.before_send', function () { throw new \RuntimeException('Thrown before sending!'); }); $client->send(array($request)); }