/** * Send a POST request * * @param string $uri * @param array $post_data * @param array $headers * @return \Guzzle\Http\Message\Response */ public function post($uri, $post_data = array(), $headers = array()) { // add the authorization header $headers['Authorization'] = "Bearer {$this->_generateBearerToken()}"; $headers['X-ApplicationId'] = $this->appId; $response = $this->client->post($uri, $headers, $post_data)->setAuth('developers.chromedia', 'cfe-developers', 'Bearer')->send(); return $response; }
public function authentification($force = false) { if (!empty($this->token) && $force == false) { return true; } $request = $this->restClient->post(self::T411_API_BASE_URL . '/auth'); $request->addPostFields(array('username' => $this->username, 'password' => $this->password)); $response = $request->send(); $result = json_decode($response->getBody(true)); $this->handleResponse($result); $this->token = $result->token; return $result; }
/** * @param string $relation * @param array $parameters * @throws ServiceUnavailableHttpException * @return Navigator|mixed */ public function command($relation, array $parameters = [], $files = []) { $templatedUrl = $this->getRelation($relation); // expand template url + remove templated params from parameters $url = $this->renderUri($templatedUrl, $parameters); $templatedParameters = $this->uriTemplater->extract($templatedUrl, $url); $parameters = array_diff_key($parameters, $templatedParameters); try { $headers = []; if (!$files) { $headers = ['Content-Type' => 'application/json']; $parameters = json_encode($parameters); } $request = $this->guzzleClient->post($url, $headers, $parameters); $request->addPostFiles($files); $command = $this->guzzleClient->send($request); } catch (ClientErrorResponseException $e) { throw $e; } switch ($command->getContentType()) { case 'application/hal+json': $response = new Navigator($command->json()); break; case 'application/json': $response = $command->json(); break; default: $response = $command->getBody(true); break; } return $response; }
/** * @param array $data * Data that will be sent to the Graph * * @param string|null $path * The path of the request. Some operations like Batch don't need it. * If the $path is complete, with all query parameters, $data will be ignored * * @return \stdClass[] */ public function curl($data = array(), $path = '', $method = 'post') { $fails = 0; $this->guzzle_client->setBaseUrl('https://graph.facebook.com'); if (substr($path, 0, 26) != 'https://graph.facebook.com') { $data['access_token'] = $this->getAccessToken(); } do { if ($fails > 0) { usleep($fails * 20000 + rand(0, 1000000)); } $result = null; switch ($method) { case 'get': $path = $this->buildQuery($data, $path); $request = $this->guzzle_client->get($path); break; case 'post': foreach ($data as &$data_param) { if (is_array($data_param)) { $data_param = json_encode($data_param); } } $request = $this->guzzle_client->post($path, array(), $data); break; default: throw new \Exception('Available methods: post or get'); break; } try { $response = $request->send(); } catch (ClientErrorResponseException $e) { throw new OAuthException('Error', 0, $e); } if ($fails > self::MAX_REQUEST_ATTEMPTS) { throw new \Exception('Failed to connect to server ' . self::MAX_REQUEST_ATTEMPTS . ' times'); } $fails++; $result = json_decode($response->getBody(true), false, 512, JSON_BIGINT_AS_STRING); } while ($this->isNotValidResponse($result)); if (isset($result->paging) && isset($result->paging->next) && $result->paging->next != null) { //$next_result = $this->curl(array(), $result->paging->next, 'get'); usleep(1000); $next_result = $this->curl([], $result->paging->next, 'get'); /** @noinspection PhpUndefinedFieldInspection */ $result->data = array_merge($result->data, $next_result->data); } return $result; }
/** * @param string $image * @param array $dimensions * @return KrakenResponse */ protected function send($image, array $dimensions = []) { switch ($this->service_type) { case 'url': $data = $this->getUrlData($image, $dimensions); break; case 'upload': $data = $this->getUploadData($image, $dimensions); break; } $this->logger->debug('Sending kraken request to ' . $this->guzzle->getBaseUrl() . ' payload: ' . print_r($data, 1)); $request = $this->guzzle->post(null, null, ['body' => $data], ['debug' => true]); $response = $request->send(); return new KrakenResponse($response); }
/** * Actually sends a request to the last.fm API * @param array $data The data to be submitted to the server * @param string $method Either a get or post HTTP request * @return \SimpleXMLElement The response XML */ private function sendRequest(array $data = [], $method = 'get') { if ($method === 'post') { $request = $this->client->post(''); $request->addPostFields($data); } else { $request = $this->client->get(''); $request->getQuery()->merge($data); } try { $response = $request->send(); } catch (BadResponseException $e) { return simplexml_load_string((string) $e->getResponse()->getBody()); } catch (CurlException $e) { return null; } return simplexml_load_string((string) $response->getBody()); }
public function execute($client = null) { if ($client == null) { $client = new GuzzleClient(); } $url = $this->protocol . '://' . $this->hostname . $this->path; switch ($this->verb) { case 'get': $request = $client->get($url); break; case 'post': $request = $client->post($url); break; case 'put': $request = $client->put($url); break; case 'delete': $request = $client->delete($url); break; } return new Response($request->send()); }
protected function execute(InputInterface $input, OutputInterface $output) { $repositoryName = $this->parseRepositoryName($input->getOption('repository')); $client = new Client($input->getOption('api-url') . '{?access_token}', array('access_token' => $input->getOption('access-token'), 'request.options' => array('Content-Type' => 'application/json'))); $client->addSubscriber(BackoffPlugin::getExponentialBackoff()); $postData = $this->generatePostData($input); if (!isset($postData['coverage'])) { $output->write(sprintf('Notifying that no code coverage data is available for repository "%s" and revision "%s"... ', $repositoryName, $postData['revision'])); } else { $output->write(sprintf('Uploading code coverage for repository "%s" and revision "%s"... ', $repositoryName, $postData['revision'])); } try { $client->post('repositories/' . $repositoryName . '/data/code-coverage{?access_token}', null, json_encode($postData))->send(); $output->writeln('Done'); return 0; } catch (BadResponseException $ex) { $output->writeln("<error>Failed</error>"); if ($ex instanceof ClientErrorResponseException) { $output->writeln('<error>' . $ex->getResponse()->getBody(true) . '</error>'); return 1; } throw $ex; } }
/** * Performs the API Call to PostMarkApp using GuzzlePHP * * @param $type * * @return string */ private function execute($type) { $client = new Client($this->_api_url); $client->setDefaultOption("headers", array('X-Postmark-Server-Token' => $this->_credentials, 'Accept' => 'application/json', 'Content-Type' => ' application/json')); $url = ""; switch ($type) { case "SEND": $url = $this->_api_send_url; break; case "BATCH": $url = $this->_api_batch_url; } $request = $client->post($url, null, json_encode($this->_send_object)); return $request->send()->json(); }
/** * Authorize the user on the remote server * @param Input $input * @return GuzzleClient */ public function authorizeRemote($input) { $client = new GuzzleClient($input['remote_url']); $client->setSslVerification(FALSE); $cookieJar = new ArrayCookieJar(); // Create a new cookie plugin $cookiePlugin = new CookiePlugin($cookieJar); // Add the cookie plugin to the client $client->addSubscriber($cookiePlugin); $post_data = array('username' => $input['username'], 'password' => $input['password'], 'remember' => 'checked', 'api' => true); $response = $client->post('login/backend', array(), $post_data)->send(); $response_json = $response->json(); if (isset($response_json['error'])) { throw new Exception($response_json['error']); } return $client; }
/** * Send POST request to API resource * * @param string $resource * @param array $params * @return array */ protected function sendPostRequest($resource, $params) { $client = new Client(); $request = $client->post($this->getServiceUrl($resource), array('Authorization' => $this->getOauthData(), 'Accept' => 'application/x-yametrika+json', 'Content-Type' => 'application/x-yametrika+json'), json_encode($params)); $response = $this->sendRequest($request)->json(); return $response; }
/** * Performs the API Call to Mandrill using GuzzlePHP * * @return string */ private function execute() { $client = new Client($this->_api_url); $this->_message_object['to'] = $this->_recipients; $this->_message_object['global_merge_vars'] = $this->_global_merge_vars; $this->_message_object['merge_vars'] = $this->_merge_vars; $this->_message_object['attachments'] = $this->_attachments; $this->_message_object['images'] = $this->_images; $this->_message_object["metadata"] = $this->_global_metadata; $this->_message_object['recipient_metadata'] = $this->_metadata; $this->_message_object['tags'] = $this->_tags; $this->_send_object['message'] = $this->_message_object; $request = $client->post($this->_api_send_url, null, json_encode($this->_send_object)); return $request->send()->json(); }
public function docUploadTestAction() { $client = new Client('https://lossync.sudoux.com/losService.svc', array('ssl.certificate_authority' => false)); $client->setDefaultOption('auth', array('dan', 'letmein!789', 'Basic')); /*$user = array( 'AuthUser' => array( 'uri' => 'https://lossync.sudoux.com/losService.svc', 'username' => 'dan', 'password' => ), 'lostype' => 0, 'apiKey' => 'AAKLPCALBX', );*/ $filePath = $this->container->get('kernel')->getRootDir() . '/../web/fff.jpg'; if (!is_file($filePath)) { $e = new \Exception('Local file not found'); $this->logger->crit($e->getMessage()); throw $e; } // first upload the file $params = array('file' => '@' . $filePath); // $request = $client->post('uploadFile'); // Set the body of the POST to stream the contents of /path/to/large_body.txt // $request->setBody(fopen('/path/to/large_body.txt', 'r')); // $response = $request->send(); $request = $client->post('uploadFile'); $request->setBody(fopen($filePath, 'r')); $response = $request->send(); $data = $response->json(); }
public static function dequeue($job, $data) { $callback_url = $data['callback_url']; $method = strtoupper($data['callback_method']); $payload = unserialize(base64_decode($data['callback_payload_base64'])); if (empty($callback_url)) { Log::warning('Empty callback URL'); return FALSE; } $client = new HttpClient(); if ($method == 'GET') { $request = $client->get($callback_url); } elseif ($method == 'POST') { $request = $client->post($callback_url, array(), $payload); } elseif ($method == 'PUT') { $request = $client->put($callback_url, array(), $payload); } elseif ($method == 'DELETE') { $request = $client->delete($callback_url); } elseif ($method == 'UPDATE') { $request = $client->update($callback_url); } elseif ($method == 'PATCH') { $request = $client->patch($callback_url); } else { QueuedHttpClient::logFailedCallback($job, $data, ['success' => false, 'message' => 'Unsupported method: ' . $method], 'hard'); return FALSE; } try { $response = $request->send(); if ($response->getStatusCode() != 200) { if ($job->attempts() > 60) { QueuedHttpClient::logFailedCallback($job, $data, $response, 'hard'); $job->delete(); } else { QueuedHttpClient::logFailedCallback($job, $data, $response, 'soft'); $job->release(60); } return $response; } // request probably successful, delete from queue $job->delete(); return $response; // these exceptions are broken out here because perhaps we want to // treat them differently in deciding whether to requeue or not } catch (CurlException $e) { // curl network and low-level exceptions QueuedHttpClient::retryLaterOrDelete($job, $data, get_class($e) . ": " . $e->getResponse(), 60, 60 * 24); // retry every minute for up to 24 hours } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { // server 4xx exceptions QueuedHttpClient::retryLaterOrDelete($job, $data, get_class($e) . ": " . $e->getResponse(), 60, 60); // retry every minute for up to an hour } catch (Guzzle\Http\Exception\ServerErrorResponseException $e) { // server 5xx exceptions QueuedHttpClient::retryLaterOrDelete($job, $data, get_class($e) . ": " . $e->getResponse(), 60, 60 * 24); // retry every minute for up to 24 hours } catch (Guzzle\Common\Exception\RuntimeException $e) { // result most likely wasn't in JSON format QueuedHttpClient::retryLaterOrDelete($job, $data, get_class($e) . ": " . $e->getMessage(), 60, 10); // retry every minute for up to ten minutes } catch (Exception $e) { // unknown other error QueuedHttpClient::retryLaterOrDelete($job, $data, get_class($e) . ": " . $e->getMessage(), 60, 60 * 24); // retry every minute for up to 24 hours } }