/** * {@inheritdoc} */ public function post($url, array $headers = array(), $content = '') { $headers['content-type'] = 'application/json'; $request = $this->client->post($url, $headers, $content); $this->response = $request->send(); return $this->response->getBody(true); }
/** * {@inheritdoc} */ public function postContent($url, array $headers = array(), array $content = array(), array $files = array()) { $request = $this->client->post($url, $headers, $content); foreach ($files as $key => $file) { $request->addPostFile($key, $file); } return $this->sendRequest($request); }
public function track($trackingNumber) { try { $response = $this->httpClient->post($this->url, array(), array('API' => 'TrackV2', 'XML' => $this->createTrackRequestXml($trackingNumber)))->send(); } catch (HttpException $e) { throw Exception::createFromHttpException($e); } return $this->parseTrackResponse($response->getBody(true), $trackingNumber); }
public function track($trackingNumber) { $body = $this->createAuthenticationXml() . $this->createTrackXml($trackingNumber); try { $response = $this->httpClient->post($this->url, array(), $body)->send(); } catch (HttpException $e) { throw Exception::createFromHttpException($e); } return $this->parse($response->getBody(true)); }
public function call($wrappedClass, $method, array $params = array()) { $request = $this->client->post(sprintf('/%s/%s', str_replace('\\', '/', $wrappedClass), $method), $params); $auth = $this->getAuthConfig($this->auth); if ($auth) { $request->setAuth($auth['login'], $auth['pass'], $auth['type']); } $response = $request->send(); return $response->getBody(); }
/** * {@inheritdoc} */ public function post($url, $content = '') { $request = $this->client->post($url, [], $content); try { $this->response = $request->send(); } catch (RequestException $e) { $this->response = $e->getResponse(); $this->handleError(); } return $this->response->getBody(true); }
/** * {@inheritDoc} */ public function format($string) { $request = $this->client->post('markdown', null, json_encode(array('text' => $string))); try { $response = $request->send(); } catch (BadResponseException $e) { $response = $e->getResponse(); $json = $response->json(); throw new RuntimeException(sprintf('Request to Github failed: %s [%d]', $json['message'], $response->getStatusCode())); } return $response->getBody(true); }
/** * @param array $postData * @return \Guzzle\Http\Message\EntityEnclosingRequestInterface|\Guzzle\Http\Message\RequestInterface * @throws Exceptions\BadServiceException * @throws Exceptions\AppNexusAPIException */ private function buildRequestObject(array $postData = array()) { $where = $this->where; if (isset($where['since'])) { if (!$this->getServiceObject($this->getService())->supportsSince()) { throw new BadServiceException(sprintf("[%s] does not support `since()`", $this->getService())); } switch ($this->getService()) { case self::SERVICE_LANGUAGE: $key = 'min_last_activity'; break; default: $key = 'min_last_modified'; break; } $where[$key] = $where['since']; unset($where['since']); } $uri = sprintf("/%s?%s", $this->getService(), http_build_query($where)); switch ($this->getServiceObject($this->getService())->getRequestVerb()) { case 'get': return $this->client->get($uri, array('Authorization' => $this->token)); break; case 'post': return $this->client->post($uri, array('Authorization' => $this->token), json_encode($postData)); break; default: throw new AppNexusAPIException(sprintf("Unknown verb [%s]", $this->getServiceObject($this->getService())->getRequestVerb())); } }
/** * {@inheritDoc} */ public function postJson($path, $postBody, array $parameters = array(), array $headers = array()) { $parameters = $this->buildQueryParameters($parameters); $request = $this->client->post($path, $headers, null, $parameters); $request->setBody($postBody, 'application/json'); return $this->request($request); }
/** * {@inheritdoc} */ public function updateTranslation($masterfile, $lang, $filePath) { $url = $this->getApiUrl('translation', array('master-file-name' => $masterfile, 'language-tag' => $lang)); $response = $this->httpClient->post($url)->addPostFile('file', $filePath)->send(); if (!$response->isSuccessful()) { throw new RuntimeException('Something went wrong dialing with the api server: ' . $response->getBody()); } return $response->getBody(true); }
public function enableOauthAuthentication($key, $secret, $accessToken = null, $code = null) { $this->key = $key; $this->secret = $secret; $this->accessToken = $accessToken; $this->code = $code; if (!$accessToken && !$code) { throw new InvalidArgumentException(sprintf("No OAuth code or access token given, please visit %s to generate a new code", "https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id={$key}")); } elseif (!$accessToken && $code) { $request = $this->client->post('oauth2/token', array(), array('code' => $this->code, 'grant_type' => 'authorization_code', 'client_id' => $this->key, 'client_secret' => $this->secret)); try { $response = $request->send(); } catch (ClientErrorResponseException $e) { $this->handleBadResponseExceptions($e); } $token = $response->json(); $this->accessToken = $token['access_token']; } $this->client->setDefaultOption('request.options/headers/Authorization', 'Bearer ' . $this->accessToken); }
/** * {@inheritdoc} */ public function send(MessageInterface $message) { // Validate we have everything we need foreach (array('token', 'room', 'from') as $variable) { if (empty($this->{$variable})) { throw new InvalidArgumentException("Invalid `{$variable}`"); } } // Build up the data we are sending to Hipchat $data = array('room_id' => $this->getRoom(), 'from' => $this->getFrom(), 'message' => $message->getMessage(), 'message_format' => $message->getMessageFormat(), 'notify' => $message->getNotification(), 'color' => $message->getBackgroundColor(), 'format' => 'json'); $data = http_build_query($data, '', '&'); return $this->http->post($this->getUri(), $this->getHeaders(), $data)->send(); }
private function refreshToken() { $request = $this->client->post('https://accounts.google.com/o/oauth2/token', array(), array('client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'refresh_token' => $this->refreshToken, 'grant_type' => 'refresh_token')); try { $response = $request->send(); } catch (ClientErrorResponseException $e) { $this->handleBadResponseExceptions($e); } $token = $response->json(); if (!isset($token['access_token'])) { throw new RuntimeException('Invalid token response received from Google Drive'); } $this->enableOAuth2Authentication($this->clientId, $this->clientSecret, $token['access_token'], $this->refreshToken); }
/** * @param AccessToken $token * @return AcccessToken */ public function getToken(AccessToken $token = null) { if ($token && $token->getRefreshToken()) { $this->body['grant_type'] = 'refresh_token'; $this->body['refresh_token'] = $token->getRefreshToken(); } else { $this->buildBody(); } $request = $this->client->post($this->tokenRequestPath, $this->headers, $this->body); $response = $request->send(); $data = $response->json(); $refreshToken = isset($data['data']['refresh_token']) ?: ''; return new AccessToken($data['data']['access_token'], $refreshToken, $data['data']['expires_in']); }
/** * {@inheritdoc} */ public function post($url, $content = '') { $request = $this->client->post($url); if (is_array($content)) { $request->setBody(json_encode($content), 'application/json'); } else { $request->setBody($content); } try { $this->response = $request->send(); } catch (RequestException $e) { $this->response = $e->getResponse(); $this->handleError(); } return $this->response->getBody(true); }
/** * Create a white label user with the following identifier * * @param string $identifier Unique and permanent identifier for the user in the white label application. This identifier * will be used in all future communications regarding this user. As such, it cannot ever change. * * @return WhiteLabelUser * @throws CommunicationError If there was an error communicating with the endpoint * @throws InvalidCredentialsError If the credentials supplied to the endpoint were invalid * @throws InvalidRequestError If the endpoint proclaims the request invalid * @throws InvalidResponseError If the encrypted data is not valid JSON */ public function createWhiteLabelUser($identifier) { $body = json_encode(array("app_key" => $this->appKey, "secret_key" => base64_encode($this->getEncryptedSecretKey()), "identifier" => $identifier)); $request = $this->guzzleClient->post("/v1/users")->setBody($body, "application/json"); $request->getQuery()->add("signature", $this->cryptService->sign($body)); $data = $this->sendRequest($request); $cipher = $this->cryptService->decryptRSA($data["cipher"]); $key = substr($cipher, 0, strlen($cipher) - 16); $iv = substr($cipher, -16); $userJsonData = $this->cryptService->decryptAES($data["data"], $key, $iv); try { $userData = $this->jsonDecodeData($userJsonData); } catch (InvalidResponseError $e) { throw new InvalidResponseError("Response data is not valid JSON when decrypted", $e->getCode(), $e); } return new WhiteLabelUser($userData["qrcode"], $userData["code"]); }
/** * Post request * * @param string $path The path to query * @param array $args An array of query parameters * @return string The response body * @throws BadResponseException * @throws RuntimeException */ public function post($path, array $args = array()) { $queryDatas = $this->formatQueryParameters($args); $path = sprintf('%s%s', ltrim($path, '/'), $this->getTemplate($queryDatas['data'])); try { $request = $this->client->post(array($path, $queryDatas)); $request->setHeader('Accept', 'application/json'); $this->log($request->getRawHeaders()); $response = $request->send(); $this->log($response->getRawHeaders()); } catch (CurlException $e) { throw new RuntimeException($e->getMessage(), $e->getErrorNo(), $e); } catch (GuzzleBadResponse $e) { $response = $e->getResponse(); $ex = new BadResponseException($response->getReasonPhrase(), $e->getCode(), $e); $ex->setResponseBody($response->getBody())->setHttpStatusCode($response->getStatusCode()); throw $ex; } catch (GuzzleException $e) { throw new RuntimeException($e->getMessage(), $e->getCode(), $e); } return $response->getBody(); }
/** * Queue a request ready to send * * @param \Raven\Contracts\Request $request * @return $this */ public function queue(RequestContract $request) { $newRequest = $this->client->post($request->getUrl(), $request->getHeaders(), $request->getBody()); array_push($this->queue, $newRequest); return $this; }
function it_build_a_post_request(ClientInterface $client, RequestInterface $request) { $client->post('/resource?foo=bar', ['some headers'], ['data' => 'plop'], ['some options'])->shouldBeCalled(1)->willReturn($request); $this->setClient($client); $this->build('/resource', ['foo' => 'bar'], ['some headers'], ['data' => 'plop'], null, ['some options'])->shouldReturn($request); }
/** * Execute the request to get the access token. * * @param Guzzle\Http\ClientInterface $client * @param array $options * @return Guzzle\Http\Message\Response */ protected function executeAccessRequest(ClientInterface $client, $options) { $headers = array('Authorization' => 'Bearer ' . $this->secret); return $client->post($this->getAccessEndpoint(), $headers, $options)->send(); }
/** * @param Message\Event $event * * @return Message\Response */ public function track(Message\Event $event) { $request = $this->client->post(null, null, $this->getPostBody($event)); return $request->send(); }
/** * {@inheritdoc} * * @throws \GuzzleHttp\Exception\RequestException */ public function send($url, $message, array $headers = []) { $this->http->post($url, ['headers' => $headers, 'body' => $message]); }
/** * Sends the message currently stored in the object to the currently defined * GovTalkServer and parses the response for use later. * * Note: the return value of this method does not reflect the success of the * data transmitted to the Gateway, but that the message was transmitted * correctly and that a response was received. Applications must query * the response methods to discover more informationa about the data recieved * in the Gateway reply. * * @param mixed cRequestString If not null this will be used as the message payload * @return boolean True if the message was successfully submitted to the Gateway and a response was received. */ public function sendMessage($cRequestString = null) { if ($cRequestString !== null) { $this->fullRequestString = $cRequestString; } else { $this->fullRequestString = $this->packageGovTalkEnvelope(); } if ($this->fullRequestString) { $this->fullResponseString = $this->fullResponseObject = null; // Log the outgoing message if ($this->messageLogLocation !== null) { $ds = date('YmdHis'); $f = fopen("{$this->messageLogLocation}/{$ds}-{$this->transactionId}-request.xml", 'w'); fprintf($f, $this->fullRequestString); fclose($f); } $headers = array('Content-Type' => 'text/xml; charset=utf-8'); $httpResponse = $this->httpClient->post($this->govTalkServer, $headers, $this->fullRequestString)->send(); $gatewayResponse = (string) $httpResponse->getBody(); // Remove old usage of cURL - rather use via Guzzle as this is mockable // if (function_exists('curl_init')) { // $curlHandle = curl_init($this->govTalkServer); // curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); // curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1); // curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $this->fullRequestString); // $gatewayResponse = curl_exec($curlHandle); // curl_close($curlHandle); // } else { // $streamOptions = array( // 'http' => array( // 'method' => 'POST', // 'header' => 'Content-Type: text/xml', // 'content' => $this->fullRequestString // ) // ); // if ($fileHandle = @fopen($this->govTalkServer, 'r', false, stream_context_create($streamOptions))) { // $gatewayResponse = stream_get_contents($fileHandle); // } else { // return false; // } // } if ($gatewayResponse !== false) { // Log the incoming message if ($this->messageLogLocation !== null) { $ds = date('YmdHis'); $f = fopen("{$this->messageLogLocation}/{$ds}-{$this->transactionId}-response.xml", 'w'); // fprintf($f, $gatewayResponse); fprintf($f, $httpResponse); fclose($f); } $this->fullResponseString = $gatewayResponse; $validXMLResponse = false; if ($this->messageTransformation == 'XML') { if (isset($this->additionalXsiSchemaLocation) && $this->schemaValidation == true) { $xsiSchemaHeaders = @get_headers($this->additionalXsiSchemaLocation); if ($xsiSchemaHeaders[0] != 'HTTP/1.1 404 Not Found') { $validate = new DOMDocument(); $validate->loadXML($this->fullResponseString); if ($validate->schemaValidate($this->additionalXsiSchemaLocation)) { $validXMLResponse = true; } } else { return false; } } else { $validXMLResponse = true; } } if ($validXMLResponse === true) { $this->fullResponseObject = simplexml_load_string($gatewayResponse); } return true; } else { return false; } } else { return false; } }
/** * @throws InvalidArgumentException When any of the options "company", "collection" are not provided */ private function doRequest(array $pathParts, $data = array()) { $this->lastErrors = array(); if (!isset($data['company'])) { $data['company'] = $this->companyName; } if (!isset($data['collection'])) { $data['collection'] = $this->collectionName; } foreach (array('company', 'collection') as $key) { if (!isset($data[$key])) { throw new InvalidArgumentException(sprintf('The option "%s" must be provided.', $key)); } } if (isset($data['cols'])) { $data['cols'] = $this->encodeColumns($data['meta']); } if (isset($data['scales'])) { $data['scales'] = $this->encodeScales($data['scales']); } if (isset($opts['filters'])) { $data['filters'] = $this->encodeFilters($data['filters']); } $url = sprintf('%s/%s', $this->pathPrefix, implode('/', $pathParts)); if (isset($data['models']) && count($data['models'])) { $url = sprintf('%s/%s', $url, $this->encodeModels($data['models'])); } $useGET = !count($data); if (isset($data['_method']) && $data['_method'] === 'GET') { $useGET = true; unset($data['_method']); } if ($useGET) { $request = $this->httpClient->get($url); $query = $request->getQuery(); $query->merge($data); } else { $request = $this->httpClient->post($url); if (count($data)) { $request->addPostFields($data); } if (isset($data['inputfile']) && $data['inputfile']) { $inputFile = $data['inputfile']; $mimeType = MimeTypeGuesser::getInstance()->guess($inputFile); $request->addPostFile('inputfile', $inputFile, $mimeType); } } $request->setPort($this->port); if ($this->accessKey && $this->secretKey) { $request->setAuth($this->accessKey, $this->secretKey); } if (null !== $this->logger) { $this->logger->debug(sprintf('Sending request to Sajari engine: %s', $request)); } $response = $request->send(); if (null !== $this->logger) { $this->logger->debug(sprintf('Received response from Sajari engine: %s', $response->getBody(true))); } $this->lastRawResponse = $response->getBody(true); $jsonResponse = $response->json(); $this->lastResponse = $response; if (!$jsonResponse) { $this->lastErrors[] = 'No response'; return false; } $statusCode = (int) $jsonResponse['statusCode']; if ($statusCode === 200) { $result = true; if (isset($jsonResponse['response'])) { $result = $jsonResponse['response']; if (isset($jsonResponse['msecs'])) { $result['msecs'] = $jsonResponse['msecs']; } } return $result; } $errors = isset($jsonResponse['errors']) ? $jsonResponse['errors'] : array('Unknown error'); $this->lastErrors = array_merge($this->lastErrors, $errors); return false; }
/** * Execute the request to get the access token. * * @param Guzzle\Http\ClientInterface $client * @param array $options * @return Guzzle\Http\Message\Response */ protected function executeAccessRequest(ClientInterface $client, $options) { return $client->post($this->getAccessEndpoint(), null, $options)->send(); }