/** * @param string $endpoint * @param string $content * @param array $headers * @param array $files * @return Response */ public function send($endpoint, $content, array $headers = array(), array $files = array()) { // Make headers buzz friendly array_walk($headers, function (&$value, $key) { $value = sprintf('%s: %s', $key, $value); }); if ($files) { // HTTP query content parse_str($content, $fields); // Add files to request foreach ($files as $key => $items) { $fields[$key] = array(); foreach ($items as $name => $item) { $item = new FormUpload($item); if (!is_numeric($name)) { $item->setName($name); } $fields[$key] = $item; } } $response = $this->browser->submit($endpoint, $fields, RequestInterface::METHOD_POST, array_values($headers)); } else { // JSON content $response = $this->browser->post($endpoint, array_values($headers), $content); } return new Response($response->getStatusCode(), $response->getContent()); }
/** * Sends the message via the GCM server. * * @param mixed $data * @param array $registrationIds * @param array $options * @param string $payload_type * * @return bool */ public function send($data, array $registrationIds = array(), array $options = array(), $payload_type = 'data') { $this->responses = array(); if (!in_array($payload_type, ['data', 'notification'])) { $payload_type = 'data'; } $data = array_merge($options, array($payload_type => $data)); if (isset($options['to'])) { $this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data)); } elseif (count($registrationIds) > 0) { // Chunk number of registration ID's according to the maximum allowed by GCM $chunks = array_chunk($registrationIds, $this->registrationIdMaxCount); // Perform the calls (in parallel) foreach ($chunks as $registrationIds) { $data['registration_ids'] = $registrationIds; $this->responses[] = $this->browser->post($this->apiUrl, $this->getHeaders(), json_encode($data)); } } $this->client->flush(); foreach ($this->responses as $response) { $message = json_decode($response->getContent()); if ($message === null || $message->success == 0 || $message->failure > 0) { return false; } } return true; }
function it_parses_properly(MessageInterface $messageInterface) { $messageInterface->getContent()->willReturn(<<<JSON [{ \t"command": "settings", \t"settings": { \t\t"basePath": "\\/", \t\t"pathPrefix": "ca\\/", \t\t"ajaxPageState": { \t\t\t"theme": "bicing", \t\t\t"theme_token": "NngnJfQN6FaHhoz6tHcHih5kFdxcm0b7EeWdAgd492M" \t\t} \t}, \t"merge": true }, { \t"command": "insert", \t"method": null, \t"selector": null, \t"data": "[{\\u0022StationID\\u0022:\\u00221\\u0022,\\u0022StationName\\u0022:\\u002201 - C\\\\/ GRAN VIA CORTS CATALANES 760\\u0022,\\u0022DisctrictCode\\u0022:\\u00222\\u0022,\\u0022AddressGmapsLongitude\\u0022:\\u00222.180042000000000000\\u0022,\\u0022AddressGmapsLatitude\\u0022:\\u002241.39795200000000000\\u0022,\\u0022StationAvailableBikes\\u0022:\\u002217\\u0022,\\u0022StationFreeSlot\\u0022:\\u00222\\u0022,\\u0022AddressZipCode\\u0022:\\u002208013\\u0022,\\u0022AddressStreet1\\u0022:\\u0022Gran Via Corts Catalanes\\u0022,\\u0022AddressNumber\\u0022:\\u0022760\\u0022,\\u0022NearbyStationList\\u0022:\\u002224,369,387,426\\u0022,\\u0022StationStatusCode\\u0022:\\u0022OPN\\u0022}]", \t"settings": null }, { \t"command": "insert", \t"method": "prepend", \t"selector": null, \t"data": "", \t"settings": null }] JSON ); $this->browser->post(BicingApi::BICING_URL)->willReturn($messageInterface); $this->getSnapshot()->shouldHaveCount(1); }
/** * @inheritdoc */ public function send($apikey, $address, $amount, $ip, $referral = false) { $url = $this->buildUrl('faucet/send', $apikey); $data = http_build_query(array('address' => $address, 'amount' => $amount, 'referral' => $referral, 'ip' => $ip)); $response = $this->browser->post($url, $this->headers, $data); return new Response\FaucetSendResponse($response); }
/** * Sends the data to the given registration IDs via the GCM server * * @param \RMS\PushNotificationsBundle\Message\MessageInterface $message * @throws \RMS\PushNotificationsBundle\Exception\InvalidMessageTypeException * @return bool */ public function send(MessageInterface $message) { if (!$message instanceof AndroidMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by GCM", get_class($message))); } if (!$message->isGCM()) { throw new InvalidMessageTypeException("Non-GCM messages not supported by the Android GCM sender"); } $headers = array("Authorization: key=" . $this->apiKey, "Content-Type: application/json"); $data = array_merge($message->getGCMOptions(), array("data" => $message->getData())); // Chunk number of registration IDs according to the maximum allowed by GCM $chunks = array_chunk($message->getGCMIdentifiers(), $this->registrationIdMaxCount); // Perform the calls (in parallel) $this->responses = array(); foreach ($chunks as $registrationIDs) { $data["registration_ids"] = $registrationIDs; $this->responses[] = $this->browser->post($this->apiURL, $headers, json_encode($data)); } // If we're using multiple concurrent connections via MultiCurl // then we should flush all requests if ($this->browser->getClient() instanceof MultiCurl) { $this->browser->getClient()->flush(); } // Determine success foreach ($this->responses as $response) { $message = json_decode($response->getContent()); if ($message === null || $message->success == 0 || $message->failure > 0) { return false; } } return true; }
/** * @return Buzz\Message\Response */ public function sendQuery(Query $query, $url = self::URL) { $headers = array(); $headers[] = 'User-Agent: SBBMobile/4.8 CFNetwork/609.1.4 Darwin/13.0.0'; $headers[] = 'Accept: application/xml'; $headers[] = 'Content-Type: application/xml'; return $this->browser->post($url, $headers, $query->toXml()); }
/** * {@inheritdoc} */ public function post($url, array $headers = array(), $content = '') { $response = $this->browser->post($url, $headers, $content); if (!$response->isSuccessful()) { throw $this->handleResponse($response); } return $response->getContent(); }
public function isMarkupValid($content) { $response = $this->browser->post('https://validator.w3.org/nu/?out=json', ['Content-Type' => 'text/html', 'User-Agent' => 'w3c api'], $content); $data = json_decode($response->getContent()); $errors = array_filter($data->messages, function ($message) { return $message->type === 'error'; }); return count($errors) == 0; }
/** * @param string $endpoint * @param string $content * @param array $headers * @return Response */ public function send($endpoint, $content, array $headers = array()) { // Make headers buzz friendly array_walk($headers, function (&$value, $key) { $value = sprintf('%s: %s', $key, $value); }); $response = $this->browser->post($endpoint, array_values($headers), $content); return new Response($response->getStatusCode(), $response->getContent()); }
public function call(array $args) { $args['userkey'] = $this->apiKey; $response = $this->browser->post($this->apiUrl, [], $args); $data = json_decode($response->getContent(), true); if (isset($data['error_code'])) { throw new ApiCallException($data['error_desc'], $data['error_code']); } return $data; }
/** * Common post request for all API calls * * @param string $resource The path to the resource wanted. For example v2/room * @param array $content Parameters be posted for example: * array( * 'name' => 'Example name', * 'privacy' => 'private', * 'is_archived' => 'false', * 'is_guest_accessible' => 'false', * 'topic' => 'New topic', * ) * * @return array Decoded array containing response * @throws Exception\RequestException */ public function post($resource, $content) { $url = $this->baseUrl . $resource; $headers = array('Content-Type' => 'application/json', 'Authorization' => $this->auth->getCredential()); $response = $this->browser->post($url, $headers, json_encode($content)); if ($this->browser->getLastResponse()->getStatusCode() > 299) { throw new RequestException(json_decode($this->browser->getLastResponse()->getContent(), true)); } return json_decode($response->getContent(), true); }
/** * {@inheritDoc} */ public function flush() { if (!$this->data['gauges'] && !$this->data['counters']) { return; } try { $this->browser->post('https://metrics-api.librato.com/v1/metrics', array('Authorization: Basic ' . base64_encode($this->username . ':' . $this->password), 'Content-Type: application/json'), json_encode($this->data)); $this->data = array('gauges' => array(), 'counters' => array()); } catch (\Exception $e) { } }
/** * {@inheritdoc} */ public function post($url, $content = '') { $headers = []; if (is_array($content)) { $content = json_encode($content); $headers[] = 'Content-Type: application/json'; } $response = $this->browser->post($url, $headers, $content); $this->handleResponse($response); return $response->getContent(); }
/** * {@inheritDoc} */ public function search($query, $page = null) { try { $response = $this->browser->post($this->getUrl(), array(), $this->getQuery($query)); } catch (\Exception $e) { throw new ConnectionException(sprintf('Could not connect to "%s"', $this->getUrl()), 0, $e); } if ($response->getStatusCode() != 200) { throw new UnexpectedResponseException(sprintf('Unexpected response: %s (%d)', $response->getReasonPhrase(), $response->getStatusCode())); } return $this->transformResponse($response->getContent()); }
/** {@inheritdoc} */ public function send($uri, $payload) { try { /** @var $response Response */ $response = $this->browser->post($uri, $this->getHeaders(true), $payload); } catch (RuntimeException $e) { throw TcpException::transportError($e); } if ($response->getStatusCode() !== 200) { throw HttpException::httpError($response->getReasonPhrase(), $response->getStatusCode()); } return $response->getContent(); }
/** * Execute an Api request * * @param string $endpoint * @param array $payload * @param array $options * @return mixed */ public function execute($endpoint, array $payload, array $options = []) { $endpoint = $this->baseEndpoint . $endpoint; // set a timeout if applicable if (isset($options['timeout'])) { $this->transport->getClient()->setTimeout((int) $options['timeout']); } else { if (isset($this->timeout)) { $this->transport->getClient()->setTimeout((int) $this->timeout); } } $response = $this->transport->post($endpoint, $this->getHeaders(), json_encode(['meta' => ['when' => date('Y-m-d H:i:s'), 'server' => gethostname()], 'data' => $payload])); return json_decode($response->getContent(), true); }
/** * Calls an HTTP POST function to verify if the user's guess was correct * * @param string $remoteIp * @param string $challenge * @param string $response * @throws Exception * @return boolean */ public function checkAnswer($remoteIp, $challenge, $response) { if (empty($remoteIp)) { throw new CaptchaException('RemoteIp missing'); } $headers = array('User-Agent' => 'solvemedia/PHP', 'Content-Type' => 'application/x-www-form-urlencoded', 'Connection' => 'close'); $content = array('privatekey' => $this->privateKey, 'remoteip' => $remoteIp, 'challenge' => $challenge, 'response' => $response); $browser = new Browser(); try { /** @var Response $resp */ $resp = $browser->post(self::ADCOPY_VERIFY_SERVER, $headers, http_build_query($content)); } catch (Exception $e) { throw new CaptchaException('Failed to check captcha', 500, $e); } if (!$resp->isSuccessful()) { throw new CaptchaException('Error: ' . $resp->getStatusCode()); } /** * 0: true|false * 1: errorMessage (optional) * 2: hash */ $answers = explode("\n", $resp->getContent()); $success = filter_var($answers[0], FILTER_VALIDATE_BOOLEAN); if (!$success) { return new CaptchaResponse($success, $answers[1]); } $hashMaterial = $answers[0] . $challenge . $this->hashKey; $hash = sha1($hashMaterial); if ($hash != $answers[2]) { throw new CaptchaException('Hash verification error'); } return new CaptchaResponse($success); }
public function send(MessageInterface $message) { if (!$message instanceof WindowsphoneMessage) { throw new InvalidMessageTypeException(sprintf("Message type '%s' not supported by MPNS", get_class($message))); } $headers = array('Content-Type: text/xml', 'X-WindowsPhone-Target: ' . $message->getTarget(), 'X-NotificationClass: ' . $message->getNotificationClass()); $xml = new \SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><wp:Notification xmlns:wp="WPNotification" />'); $msgBody = $message->getMessageBody(); if ($message->getTarget() == WindowsphoneMessage::TYPE_TOAST) { $toast = $xml->addChild('wp:Toast'); $toast->addChild('wp:Text1', htmlspecialchars($msgBody['text1'], ENT_XML1 | ENT_QUOTES)); $toast->addChild('wp:Text2', htmlspecialchars($msgBody['text2'], ENT_XML1 | ENT_QUOTES)); } $response = $this->browser->post($message->getDeviceIdentifier(), $headers, $xml->asXML()); return $response->isSuccessful(); }
/** * @param UserInterface $user * @param NamedNumberInterface[] $recipient * @param string $coverPage * @param string $coverPageText * @param string $resolution * @param \DateTime $sendTime * @param array $attachments * @return string */ public function sendFax(UserInterface $user, array $recipient, $coverPage, $coverPageText, $resolution, \DateTime $sendTime, array $attachments) { $form = new FormRequest(); $form->setResource(self::FAX_OUT_ENDPOINT); $recipients = array(); foreach ($recipient as $rec) { $recipients[] = $rec->getNumber() . ($rec->getName() ? '|' . $rec->getName() : ''); } $uploads = array(); foreach ($attachments as $attachment) { $uploads[] = new FormUpload($attachment); } $fields = array('Username' => $user->getUserNumber(), 'Password' => $user->getPassword(), 'Extension' => $user->getExtension(), 'Recipient' => $recipients, 'Coverpage' => $coverPage, 'Coverpagetext' => $coverPageText, 'Resolution' => $resolution, 'Sendtime' => $sendTime->format('d:m:y h:i'), 'Attachment' => $uploads); $form->addFields($fields); return $this->browser->post(self::FAX_OUT_ENDPOINT, $form->getHeaders(), $form->getContent()); }
/** * @param string $url * The URL to POST to * @param SiteDocument $site * The site being posted to * @param array $params * An array of keys and values to be posted * * @return mixed * The content of the response * * @throws WardenRequestException * If any error occurs */ public function post($url, SiteDocument $site, array $params = array()) { try { $this->setClientTimeout($this->connectionTimeout); // Don't verify SSL certificate. // @TODO make this optional $this->buzz->getClient()->setVerifyPeer(FALSE); if ($site->getAuthUser() && $site->getAuthPass()) { $headers = array(sprintf('Authorization: Basic %s', base64_encode($site->getAuthUser() . ':' . $site->getAuthPass()))); $this->setConnectionHeaders($headers); } $params['token'] = $this->sslEncryptionService->generateRequestToken(); $content = http_build_query($params); /** @var \Buzz\Message\Response $response */ $response = $this->buzz->post($url, $this->connectionHeaders, $content); if (!$response->isSuccessful()) { $this->logger->addError("Unable to request data from {$url}\nStatus code: " . $response->getStatusCode() . "\nHeaders: " . print_r($response->getHeaders(), TRUE)); throw new WardenRequestException("Unable to request data from {$url}. Check log for details."); } $site->setLastSuccessfulRequest(); $this->siteManager->updateDocument(); return $response->getContent(); } catch (ClientException $clientException) { throw new WardenRequestException($clientException->getMessage()); } }
/** * Calls an HTTP POST function to verify if the user's guess was correct * * @param string $remoteIp * @param string $challenge * @param string $response * @throws Exception * @return boolean */ public function checkAnswer($remoteIp, $challenge, $response) { if (empty($remoteIp)) { throw new CaptchaException('RemoteIp missing'); } $headers = array('Connection' => 'close'); $content = array('secret' => $this->privateKey, 'remoteip' => $remoteIp, 'response' => $response); $browser = new Browser(); $browser->getClient()->setVerifyPeer(false); try { /** @var Response $resp */ $resp = $browser->post(self::VERIFY_SERVER, $headers, http_build_query($content)); } catch (Exception $e) { throw new CaptchaException('Failed to check captcha', 500, $e); } if (!$resp->isSuccessful()) { throw new CaptchaException('Error: ' . $resp->getStatusCode()); } $answer = json_decode($resp->getContent()); if (!$answer) { throw new CaptchaException('Error: Invalid captcha response'); } $success = isset($answer->success) && filter_var($answer->success, FILTER_VALIDATE_BOOLEAN); if (!$success) { return new CaptchaResponse($success, 'Invalid captcha'); } return new CaptchaResponse($success); }
public function sendHeartbeat() { $ip = null; $localIps = $this->getLocalIp(); if (isset($localIps['eth0'])) { $ip = $localIps['eth0']; } elseif (isset($localIps['wlan0'])) { $ip = $localIps['wlan0']; } if (null == $ip) { throw new \Exception('No local IP available.'); } $settings = $this->em->getRepository('AppBundle:Settings')->findAll(); if (count($settings) > 0) { $settings = $settings[0]; } else { throw new \Exception('No settings provided.'); } $buzz = new Browser(); $response = $buzz->post($settings->getHeartbeatUrl(), array('Content-Type' => 'application/json'), json_encode(array('locale_ip' => $ip, 'printbox' => $settings->getPrintboxPid()))); if ($response->isSuccessful()) { return $ip; } throw new \Exception('Heartbeat failed: ' . $settings->getHeartbeatUrl() . ' ' . $response->getStatusCode() . ' ' . $response->getContent()); }
/** * request the diagram from the API. * * @throws \RuntimeException * * @return array|string */ public function request(array $request) { $url = $this->configuration['url']; if ($this->configuration['debug']) { return implode(',', $request); } if (!count($request)) { throw new \RuntimeException('No Request built for: ' . $this->path); } $response = $this->browser->post($url, [], 'dsl_text=' . urlencode(implode(',', $request))); if ($response instanceof Response && $response->isSuccessful()) { $file = $response->getContent(); return ['<info>PNG</info> http://yuml.me/' . $file, '<info>URL</info> http://yuml.me/edit/' . str_replace('.png', '', $file), '<info>PDF</info> http://yuml.me/' . str_replace('.png', '.pdf', $file), '<info>JSON</info> http://yuml.me/' . str_replace('.png', '.json', $file), '<info>SVG</info> http://yuml.me/' . str_replace('.png', '.svg', $file)]; } throw new \RuntimeException('API Error for Request: ' . $url . implode(',', $request)); }
/** * Calls an HTTP POST function to verify if the user's guess was correct * * @param string $remoteIp * @param string $challenge * @param string $response * @throws Exception * @return boolean */ public function checkAnswer($remoteIp, $challenge, $response) { $headers = array('Connection' => 'close'); $content = array('private_key' => $this->privateKey, 'session_token' => $response, 'simple_mode' => 1); $browser = new Browser(); $browser->getClient()->setVerifyPeer(false); try { /** @var Response $resp */ $resp = $browser->post(self::VERIFY_SERVER, $headers, http_build_query($content)); } catch (Exception $e) { throw new CaptchaException('Failed to send captcha', 500, $e); } if (!$resp->isSuccessful()) { throw new CaptchaException('Error: ' . $resp->getStatusCode()); } $answer = $resp->getContent(); if (!$answer) { throw new CaptchaException('Error: Invalid captcha response'); } $success = isset($answer) && filter_var($answer, FILTER_VALIDATE_INT); if (!$success) { return new CaptchaResponse($success, 'Invalid captcha'); } return new CaptchaResponse($success); }
/** * Calls API through the browser client. * * @param $method * @param $baseUrl * @param array $headers * @param string $content * * @return \Buzz\Message\Response */ protected function call($method, $baseUrl, $headers = array(), $content = '') { if (strtoupper($method) == 'GET') { return $this->browser->get($baseUrl, $headers); } else { return $this->browser->post($baseUrl, $headers, $content); } }
public function perform($url) { $curl = new Curl(); $curl->setTimeout(30); $curl->setProxy($this->proxy); $browser = new Browser($curl); return $this->serializer->decode($browser->post($url)->getContent(), 'xml'); }
/** * @param string $url * @param array $headers * @param string $content * * @return \Buzz\Message\MessageInterface|null */ private function sendRequest($url, array $headers, $content) { try { $response = $this->browser->post($url, $headers, $content); } catch (RequestException $e) { $response = null; } return $response; }
/** * @param string $act * @param array $parameters * @param string $userKey * * @return mixed */ private function request($act, array $parameters, $userKey = null) { $response = $this->browser->post(self::API_URL, [], array_merge(['host_key' => $this->hostKey, 'act' => $act, 'user_key' => null !== $userKey ? $userKey : $this->userKey], $parameters)); $data = json_decode($response->getContent(), true); // TODO: Exception management if ('error' === $data['result']) { return false; } return $data['response']; }
/** * (non-PHPdoc) * @see Connection::query() */ public function query(Request $request) { $response = null; try { $response = $this->browser->post('http://' . $this->host . ':' . $this->port, array('Content-type' => 'application/json', 'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password)), $request->getContent()); } catch (\Exception $ex) { throw new TransportException("query failed due to underlaying error: " . $ex->getMessage(), $ex->getCode(), $ex); } if ($response instanceof Response) { if ($response->getStatusCode() == 401) { throw new AuthenticationException("authentication failed!"); } $jsonResponse = new JsonResponse($response->getContent()); if ($response->getStatusCode() == 200 || $jsonResponse->getError()) { return $jsonResponse; } throw new TransportException("query failed due to invalid response status! [" . $response->getStatusCode() . "]", $response->getStatusCode()); } throw new TransportException("query failed due to empty response message!"); }
private function getAccessToken() { $params = array('grant_type' => static::GRANT_TYPE, 'scope' => static::SCOPE_URL, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret); $request = new Browser(new Curl()); $response = $request->post(static::AUTH_URL, array(), http_build_query($params)); $result = json_decode($response->getContent()); if (isset($result->error) and $result->error) { throw new \Exception($result->error_description); } return $result->access_token; }