/**
  * Create a Guzzle Request object using the given JSON parameters
  *
  * @param string $query JSON String
  * @return \Guzzle\Http\Message\RequestInterface
  * @throws \Exception
  */
 public function createRequest($query)
 {
     $client = new \Guzzle\Http\Client();
     $method = $this->httpMethod;
     $uri = $this->getBaseUrl();
     $headers = array("content-type" => "application/json");
     $options = array();
     if ($method === 'POST') {
         $postBody = $query;
         $request = $client->createRequest($method, $uri, $headers, $postBody, $options);
     } else {
         if ($method === 'GET') {
             $request = $client->createRequest($method, $uri, $headers, null, $options);
             if ($query) {
                 $queryObject = json_decode($query, true);
                 $query = $request->getQuery();
                 foreach ($queryObject as $key => $val) {
                     $query->set($key, $val);
                 }
             }
         } else {
             throw new Exception('Unexpected HTTP Method: ' . $method);
         }
     }
     return $request;
 }
Example #2
0
 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;
 }
 /**
  * @see http://explorer.nuxeo.com/nuxeo/site/distribution/current/listOperations List of available operations
  * @param string $operation
  * @return NuxeoRequest
  */
 public function newRequest($operation)
 {
     $request = $this->client->createRequest(Request::POST, $operation, $this->headers);
     $request->setAuth($this->auth->getUsername(), $this->auth->getPassword());
     $newRequest = new NuxeoRequest($request);
     return $newRequest;
 }
Example #4
0
 /**
  * {@InheritDoc}
  */
 public function send(Request $request)
 {
     $guzzleRequest = $this->client->createRequest($request->getMethod(), $request->getUri(), $request->getHeaders(), $request->getBody());
     $guzzleResponse = $guzzleRequest->send();
     $response = new Response($guzzleResponse->getStatusCode(), $guzzleResponse->getHeaders()->toArray(), $guzzleResponse->getBody(true));
     return $response;
 }
Example #5
0
 protected function restRequest($method, $location)
 {
     $headers = null;
     $body = null;
     $options = array();
     $request = $this->client->createRequest($method, $location, $headers, $body, $options);
     $response = $request->send();
     $result = $response->json();
     return $result;
 }
 /**
  * Send an http request
  *
  * @param string $method     The HTTP method
  * @param string $url        The url to send the request to
  * @param array  $parameters The parameters for the request (assoc array)
  * @param array  $headers    The headers for the request (assoc array)
  *
  * return mixed
  */
 public function request($method, $url, array $parameters = null, array $headers = null)
 {
     $request = $this->client->createRequest($method, $url, $headers, $parameters);
     try {
         $response = $request->send();
     } catch (\Exception $e) {
         $response = $e->getResponse();
         throw new ApiException($response->getStatusCode(), $response->getBody(true));
     }
     return $response->json();
 }
Example #7
0
 /**
  * {@inheritdoc}
  */
 public function request($uri, $data = [], $method = 'GET', $options = [], $headers = [])
 {
     $request = $this->client->createRequest($method, $uri, $headers, $data, $options);
     if (!in_array($method, ['POST', 'PUT'], true)) {
         $request->getQuery()->merge($data);
     }
     $this->preprocessRequest($request);
     try {
         $response = $request->send();
     } catch (BadResponseException $e) {
         $response = $e->getResponse();
     }
     return $response;
 }
 /**
  *  Override ti add OVH auth
  *
  * @param $method
  * @param null $uri
  * @param null $headers
  * @param null $body
  * @return \Guzzle\Http\Message\Request
  */
 public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
 {
     $request = parent::createRequest($method, $uri, $headers, $body);
     // see http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
     #$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
     // Add OVH auth headers
     $hTimestamp = $this->getTimestamp();
     # SIG = "$1$" + sha1.hex(AS+"+"+CK+"+"+METHOD+"+"+QUERY+"+"+BODY +"+"+TSTAMP)
     #var_dump($body);
     #print $body;
     #die();
     #if ($method == "POST")
     #    $baseSig = Keyring::getAppSecret() . '+' . Keyring::getConsumerKey() . '+' . $method . '+' . $request->getUrl() . '+' . '' . '+' . $hTimestamp;
     #else
     $baseSig = Keyring::getAppSecret() . '+' . Keyring::getConsumerKey() . '+' . $method . '+' . $request->getUrl() . '+' . $body . '+' . $hTimestamp;
     #
     #print $baseSig . "\n";
     $sig = '$1$' . sha1($baseSig);
     #print $sig . "\n";
     $request->addHeader('X-Ovh-Application', Keyring::getAppKey());
     $request->addHeader('X-Ovh-Timestamp', $hTimestamp);
     $request->addHeader('X-Ovh-Consumer', Keyring::getConsumerKey());
     $request->addHeader('X-Ovh-Signature', $sig);
     return $request;
 }
Example #9
0
 protected function request($type, $path, $headers = array(), $body = null, $options = array())
 {
     $this->initializeGuzzle();
     $request = $this->guzzle->createRequest($type, $path, $headers, $body, $options);
     try {
         $response = $request->send();
         $responseBody = $response->getBody();
     } catch (ClientErrorResponseException $e) {
         $response = $e->getResponse();
         $responseBody = $response->getBody();
         $message = $responseBody;
         $errorCode = $response->getStatusCode();
         $jsonResponse = json_decode($responseBody, true);
         if (isset($jsonResponse[0]) && isset($jsonResponse[0]['message'])) {
             $message = $jsonResponse[0]['message'];
         }
         $fields = array();
         if (isset($jsonResponse[0]) && isset($jsonResponse[0]['fields'])) {
             $fields = $jsonResponse[0]['fields'];
         }
         $this->log->error($message, array('response' => $responseBody, 'fields' => $fields));
         throw $this->getExceptionForSalesforceError($message, $errorCode, $fields);
     }
     return $responseBody;
 }
 /**
  * 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;
 }
Example #11
0
 /**
  * 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();
 }
Example #12
0
 /**
  * Sends a request to the API
  *
  * @param [string] $url    URL for API request
  * @param [string] $method Request method (i.e. PUT, POST, DELETE, or GET)
  * @param [array]  $data   Options for request
  * @return [Guzzle\Http\Message\Response] $response
  */
 public static function send($url, $method, $data = array())
 {
     // Create a new Guzzle\Http\Client
     $browser = new Browser();
     $browser->setUserAgent(self::userAgent());
     $options = self::processOptions($data);
     $request = $browser->createRequest($method, $url, null, null, $options);
     if (!empty($data['postdata'])) {
         foreach ($data['postdata'] as $k => $v) {
             $request->setPostField($k, $v);
         }
     }
     if (!empty($data['cookies'])) {
         foreach ($data['cookies'] as $k => $v) {
             $request->addCookie($k, $v);
         }
     }
     if (!empty($data['headers'])) {
         foreach ($data['headers'] as $k => $v) {
             $request->setHeader($k, $v);
         }
     }
     if (!empty($data['body']) && method_exists($request, 'setBody')) {
         $request->setBody(json_encode($data['body']));
     }
     $debug = '#### REQUEST ####' . PHP_EOL;
     $debug .= $request->getRawHeaders();
     Terminus::getLogger()->debug('Headers: {headers}', array('headers' => $debug));
     if (isset($data['body'])) {
         Terminus::getLogger()->debug('Body: {body}', array('body' => $data['body']));
     }
     $response = $request->send();
     return $response;
 }
Example #13
0
 /**
  * @When /^I request "([^"]*)"(?: using HTTP "([^"]*)")?$/
  */
 public function request($path, $method = 'GET')
 {
     $this->prevRequestedPath = $path;
     if (empty($this->requestHeaders['Accept'])) {
         $this->requestHeaders['Accept'] = 'application/json';
     }
     // Add override method header if specified in the list of override verbs
     if (array_key_exists($method, $this->getOverrideVerbs())) {
         $this->setOverrideMethodHeader($method);
         $method = $this->getOverrideVerbs()[$method];
     }
     $request = $this->client->createRequest($method, $path, $this->requestHeaders);
     if ($this->requestBody) {
         $request->setBody($this->requestBody);
         $this->requestBody = null;
     }
     try {
         $response = $request->send();
     } catch (Exception $e) {
         $response = $e->getResponse();
     }
     $this->responses[] = $response;
     // Create a fresh client
     $this->createClient();
 }
Example #14
0
 /**
  * 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;
 }
 /**
  * {@inheritDoc}
  */
 public function createRequest($url, $parameters, $httpMethod = 'GET')
 {
     if ($httpMethod == 'POST' || $httpMethod == 'DELETE') {
         return $this->client->createRequest($httpMethod, $url, $this->options['headers'], $parameters);
     } else {
         return $this->client->createRequest($httpMethod, $url, $this->options['headers'], $this->options['body'], $parameters);
     }
 }
 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('');
 }
Example #17
0
 /**
  * @param string $id
  * @return Entity\PlaylistPagination
  */
 public function getUserPlaylists($id)
 {
     $request = $this->guzzleClient->createRequest('GET', sprintf('/v1/users/%s/playlists', $id));
     $response = $this->sendRequest($request)->json();
     $hydrators = new AggregateHydrator();
     $hydrators->add(new Hydrator\PaginationHydrator());
     $hydrators->add(new Hydrator\PaginatedPlaylistCollectionHydrator());
     return $hydrators->hydrate($response, new Entity\PlaylistPagination());
 }
Example #18
0
 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('');
 }
Example #19
0
 /**
  * @param Url $url
  * @return \Guzzle\Http\Message\Response
  */
 protected function executeRequest(Url $url)
 {
     $guzzle = new GuzzleClient();
     $guzzle->getEventDispatcher()->addListener('request.error', function (Event $event) {
         if ($event['response']->getStatusCode() != 200) {
             $event->stopPropagation();
         }
     });
     return $guzzle->createRequest('GET', $url)->send();
 }
Example #20
0
 /**
  * @param $method
  * @param $uri
  * @return \Guzzle\Http\Message\RequestInterface
  */
 private function prepareRequest($method, $uri)
 {
     $request = $this->client->createRequest($method, $uri);
     if ($this->basicAuthUsername !== null and $this->basicAuthPassword != null) {
         $request->setAuth($this->basicAuthUsername, $this->basicAuthPassword);
     } elseif (!empty($this->access_token)) {
         $request->addHeader('Authorization', 'Bearer ' . $this->access_token);
     }
     return $request;
 }
 /**
  * Creates a request.
  *
  * @param  string $method HTTP method. Defaults to GET
  * @param  string|array $uri Resource URI.
  * @param  callback $callback Callback to call when request is complete.
  * @param  string|array $falseAlarms False positives checks.
  * @param  array $options Array of options to apply to the request.
  * @return RequestInterface
  */
 public function createRequest($method = 'GET', $uri = null, $callback = null, $falseAlarms = array(), array $options = array())
 {
     if (is_callable($callback)) {
         if (!is_array($falseAlarms)) {
             $falseAlarms = array($falseAlarms);
         }
         $callback = $this->wrapCallback($callback, $falseAlarms);
         $options['events'] = array('request.complete' => $callback);
     }
     return parent::createRequest($method, $uri, null, null, $options);
 }
Example #22
0
 public function testCanSendCustomRequests()
 {
     $this->getServer()->flush();
     $this->getServer()->enqueue("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n");
     $request = $this->client->createRequest('PROPFIND', $this->getServer()->getUrl(), array('Content-Type' => 'text/plain'), 'foo');
     $response = $request->send();
     $requests = $this->getServer()->getReceivedRequests(true);
     $this->assertEquals('PROPFIND', $requests[0]->getMethod());
     $this->assertEquals(3, (string) $requests[0]->getHeader('Content-Length'));
     $this->assertEquals('foo', (string) $requests[0]->getBody());
 }
Example #23
0
 /**
  * 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;
 }
 /**
  * Inject Guzzle in this test class
  * And set up the given client for use on
  * Damn Vulnerable Web Application... A vulnerable application
  * without API...
  * Difficulty resided in finding the way of using
  * cookies and correct documentation for all methods.
  */
 public function __construct()
 {
     parent::__construct();
     //prepare a cookie jar
     $jar = new ArrayCookieJar();
     $cookiePlugin = new CookiePlugin($jar);
     //get a guzzle instance
     $this->_dvwa_guzzle = new Client();
     $this->_dvwa_guzzle->setBaseUrl($this->DVWA_URL);
     $this->_dvwa_guzzle->setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36");
     $this->_dvwa_guzzle->addSubscriber($cookiePlugin);
     //first request/response exchange to get CSRF token
     $request = $this->_dvwa_guzzle->get('login.php', null, ["allow_redirects" => false]);
     $response = $request->send();
     $str = $response->getBody();
     preg_match($this->USER_TOKEN_REGEX, $str, $matches);
     $user_token = $matches[1];
     //second exchange to login
     $request = $this->_dvwa_guzzle->createRequest('POST', 'login.php', null, ['username' => 'admin', 'password' => 'password', 'Login' => 'Login', 'user_token' => $user_token], ["allow_redirects" => true]);
     $request->send();
 }
 /**
  * @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);
     }
 }
Example #26
0
 public function push($remoteId)
 {
     $remotes = $this->config->getArray('push.remote');
     if (!isset($remotes[$remoteId])) {
         throw new \InvalidArgumentException("Remote 'remote' does not exist");
     }
     $remoteUrl = $remotes[$remoteId]['url'];
     $connections = $this->connectionService->findAll();
     $serializer = SerializerBuilder::create()->build();
     $serializedConnections = $serializer->serialize($connections, 'json');
     $client = new Client();
     $request = $client->createRequest('POST', $remoteUrl, array('Content-Type' => 'application/json', 'User-Agent' => 'JANUS Guzzle HTTP Client (see: https://github.com/janus-ssp/janus)'), $serializedConnections, $this->config->getArray('push.requestOptions'));
     return $request->send()->__toString();
 }
Example #27
0
 private function sendRequest($input, $additionalInput = '')
 {
     if (!$this->connectorGuid || !$this->userGuid || !$this->apiKey) {
         throw new \Exception('Missing parameters, please check your config file.');
     }
     $client = new Client();
     $url = "https://api.import.io/store/connector/" . $this->connectorGuid . "/_query?_user="******"&_apikey=" . urlencode($this->apiKey);
     $data = array("input" => $input);
     if ($additionalInput) {
         $data["additionalInput"] = $additionalInput;
     }
     $request = $client->createRequest('POST', $url);
     $request->setBody(json_encode($data), 'application/json');
     return $request->send()->json();
 }
 /**
  * @param string $uri
  * @param array  $body
  * @param array  $headers
  * @param string $method
  * @return mixed
  * @throws HttpException
  */
 public function request($uri, $body, $headers, $method)
 {
     try {
         $client = new Client();
         if ($this->debug) {
             $logPlugin = new \Guzzle\Plugin\Log\LogPlugin($this->httpLogAdapter, \Guzzle\Log\MessageFormatter::DEBUG_FORMAT);
             $client->addSubscriber($logPlugin);
         }
         $request = $client->createRequest($method, $uri, $headers, $body);
         $response = $request->send();
         return $response->json();
     } catch (ClientErrorResponseException $e) {
         throw new HttpException($e);
     }
 }
Example #29
0
 /**
  *  Override ti add Zelift auth
  *
  * @param $method
  * @param null $uri
  * @param null $headers
  * @param null $body
  * @return \Guzzle\Http\Message\Request
  */
 public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
 {
     $request = parent::createRequest($method, $uri, $headers, $body);
     // see http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
     #$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
     // Add Zelift auth headers
     $hTimestamp = $this->getTimestamp();
     $baseSig = Keyring::getAppSecret() . '+' . Keyring::getConsumerKey() . '+' . $method . '+' . $request->getUrl() . '+' . $body . '+' . $hTimestamp;
     $sig = '$1$' . sha1($baseSig);
     $request->addHeader('X-Zelift-Application', Keyring::getAppKey());
     $request->addHeader('X-Zelift-Timestamp', $hTimestamp);
     $request->addHeader('X-Zelift-Consumer', Keyring::getConsumerKey());
     $request->addHeader('X-Zelift-Signature', $sig);
     return $request;
 }
Example #30
0
 public static function send($url, $method, $data = array())
 {
     // create a new Guzzle\Http\Client
     $browser = new Browser();
     $browser->setUserAgent(self::userAgent());
     $options = array();
     $options['allow_redirects'] = @$data['allow_redirects'] ?: false;
     $options['json'] = @$data['json'] ?: false;
     if (@$data['body']) {
         $options['body'] = $data['body'];
         if (\Terminus::get_config("debug")) {
             \Terminus\Loggers\Regular::debug($data['body']);
         }
     }
     $options['verify'] = false;
     $request = $browser->createRequest($method, $url, null, null, $options);
     if (!empty($data['postdata'])) {
         foreach ($data['postdata'] as $k => $v) {
             $request->setPostField($k, $v);
         }
     }
     if (!empty($data['cookies'])) {
         foreach ($data['cookies'] as $k => $v) {
             $request->addCookie($k, $v);
         }
     }
     if (!empty($data['headers'])) {
         foreach ($data['headers'] as $k => $v) {
             $request->setHeader($k, $v);
         }
     }
     if (\Terminus::get_config("debug")) {
         $debug = "#### REQUEST ####" . PHP_EOL;
         $debug .= $request->getRawHeaders();
         \Terminus\Loggers\Regular::debug($debug);
         if (isset($data['body'])) {
             \Terminus\Loggers\Regular::debug($data['body']);
         }
     }
     if (getenv("BUILD_FIXTURES")) {
         Fixtures::put("request_headers", $request->getRawHeaders());
     }
     $response = $request->send();
     if (getenv("BUILD_FIXTURES")) {
         Fixtures::put(array($url, $method, $data), $response);
     }
     return $response;
 }