public function testCitiesListContainsAmsterdam()
 {
     $uri = "http://localhost:8000";
     $response = Request::get($uri)->send();
     $this->assertEquals("application/json", $response->headers["Content-Type"]);
     $this->assertContains("Amsterdam", $response->body);
 }
예제 #2
1
 private function sendRequest($url, $data, array $options = null, $auth = null, $apiKey = null)
 {
     array_merge($this->_headers, $options);
     if ($this->_method == GET) {
         $url = $url . http_build_query($data);
         $this->_result = Request::get($url)->send();
     } else {
         if ($this->_method == POST) {
             if (isset($apiKey)) {
                 $url .= array_keys($apiKey)[0] . "=" . array_values($apiKey)[0];
             }
             $request = Request::post($url);
             foreach ($this->_headers as $key => $hdr) {
                 $request = $request->addHeader($key, $hdr);
             }
             if ($this->headers["Content-Type"] = "application/x-www-form-urlencoded" and is_array($data)) {
                 $request = $request->body(http_build_query($data));
             } else {
                 $request = $request->body($data);
             }
             if (isset($auth)) {
                 $request = $request->authenticateWith(array_keys($auth)[0], array_values($auth)[0]);
             }
             $this->_result = $request->send();
         }
     }
 }
 /**
  * @param CreateOrderRequest $request
  * @return ApiError|CreateOrderResponse
  */
 public function createOrder(CreateOrderRequest $request)
 {
     $payload = array('merchantId' => $this->merchantId, 'apiId' => $this->apiId, 'orderId' => $request->getOrderId(), 'payCurrency' => $request->getPayCurrency(), 'payAmount' => $request->getPayAmount(), 'receiveAmount' => $request->getReceiveAmount(), 'description' => $request->getDescription(), 'culture' => $request->getCulture(), 'callbackUrl' => $request->getCallbackUrl(), 'successUrl' => $request->getSuccessUrl(), 'failureUrl' => $request->getFailureUrl());
     $formHandler = new \Httpful\Handlers\FormHandler();
     $data = $formHandler->serialize($payload);
     $signature = $this->generateSignature($data);
     $payload['sign'] = $signature;
     if (!$this->debug) {
         $response = \Httpful\Request::post($this->merchantApiUrl . '/createOrder', $payload, \Httpful\Mime::FORM)->expects(\Httpful\Mime::JSON)->send();
         if ($response != null) {
             $body = $response->body;
             if ($body != null) {
                 if (is_array($body) && count($body) > 0 && isset($body[0]->code)) {
                     return new ApiError($body[0]->code, $body[0]->message);
                 } else {
                     if (isset($body->depositAddress)) {
                         return new CreateOrderResponse($body->orderRequestId, $body->orderId, $body->depositAddress, $body->payAmount, $body->payCurrency, $body->receiveAmount, $body->receiveCurrency, $body->validUntil, $body->redirectUrl);
                     }
                 }
             }
         }
     } else {
         $response = \Httpful\Request::post($this->merchantApiUrl . '/createOrder', $payload, \Httpful\Mime::FORM)->send();
         exit('<pre>' . print_r($response, true) . '</pre>');
     }
 }
 function read($pgt_iou)
 {
     $response = Request::post(Config::get('pgtservice.endpoint'), array('Username' => Config::get('pgtservice.username'), 'Password' => Config::get('pgtservice.password'), 'PGTIOU' => $pgt_iou), Mime::FORM)->addHeader('Content-Type', 'application/x-www-form-urlencoded')->send();
     $dom = new \DOMDocument();
     $dom->loadXML($response->raw_body);
     return $dom->documentElement->textContent;
 }
예제 #5
1
 /**
  * @param string $receiptData
  * @param string $sharedSecret
  * @return array
  * @throws IAPServerUnavailableException
  */
 private function postExternal($receiptData, $sharedSecret)
 {
     if (!getenv('APPLE_IAP_VERIFY_URL')) {
         throw new IAPServerUnavailableException('An endpoint for polling apple was not found. Please ensure one is set.', 100021005);
     }
     $response = Request::post(getenv('APPLE_IAP_VERIFY_URL'))->body($this->buildFormattedArray($receiptData, $sharedSecret))->sendsType(Mime::JSON)->send();
     return json_decode($response->body, true);
 }
 public function publish($topic, $data)
 {
     $body = ['topic' => $topic, 'payload' => $data];
     try {
         $request = \Httpful\Request::post('http://localhost:9999/mqtt/publish')->sendsJson()->body(json_encode($body))->send();
     } catch (\Exception $e) {
     }
 }
예제 #7
1
파일: Hipchat.php 프로젝트: laravel/envoy
 /**
  * Send the HipChat message.
  *
  * @return mixed
  */
 public function send()
 {
     $message = $this->message ?: ucwords($this->getSystemUser()) . ' ran the [' . $this->task . '] task.';
     $format = $message != strip_tags($message) ? 'html' : 'text';
     $query = ['auth_token' => $this->token];
     $payload = ['from' => $this->from, 'message' => $message, 'message_format' => $format, 'notify' => true, 'color' => $this->color];
     return Request::post('https://api.hipchat.com/v2/room/' . $this->room . '/notification?' . http_build_query($query))->sendsJson()->body(json_encode($payload))->send();
 }
예제 #8
0
 /**
  * function config to make request
  *
  * @param $params
  * @param $function
  * @param $type (only allow get post put delete head and options)
  * @return bool
  */
 public function makeRequest($function, $params = [], $type = 'post')
 {
     if (!in_array($type, ['get', 'post', 'put', 'delete', 'head', 'options'])) {
         return false;
     }
     $url = $this->_baseApiUrl . $function;
     $this->_client = Client::$type($url);
     $header = ['Content-Type' => 'application/json'];
     $baseParams = ['ApiKey' => $this->_key, 'ApiSecretKey' => $this->_secretKey, 'ClientID' => $this->_clientId, 'Password' => $this->_password];
     $configParam = array_merge($baseParams, $params);
     return $this->_client->addHeaders($header)->body(json_encode($configParam))->send();
 }
예제 #9
0
 /**
  * @param $employee Employee
  * @return Repository[]
  */
 public function listUserRepositories($employee)
 {
     $url = self::BASE_URL . '/' . $employee->username() . '/repos';
     $response = $this->request->uri($url)->expectsJson()->send();
     $repositories = array();
     if (is_array($response->body)) {
         foreach ($response->body as $repo) {
             array_push($repositories, Repository::builder()->withId($repo->id)->withName($repo->name)->withOwnerId($employee->employeeId())->build());
         }
     }
     return $repositories;
 }
예제 #10
0
 private function fetch(&$str, $productid, $page, $count)
 {
     echo 'page is ' . $page . PHP_EOL;
     //        echo 'current str length is '.strlen($str).PHP_EOL;
     $has_more = true;
     $url = sprintf($this->url_format, $productid, $page, $count);
     $headers = ['Cookie' => '_customId=q77dbffe7014; _snmc=1; _snsr=direct%7Cdirect%7C%7C%7C; _snma=1%7oC143589353017297011%7C1435893530172%7C1435893530172%7C1435893530171%7C1%7C1; _snmp=143589353016073744; _snmb=143589353017914712%7C1435893530308%7C1435893530180%7C1; _ga=GA1.2.833540218.1435893530; _snmz=143589353016073744%7C%281049%2C3268%29'];
     try {
         $response_ = Request::get($url)->addHeaders($headers)->autoParse(false)->send();
     } catch (\Exception $e) {
         return false;
     }
     //生成一个csv文件格式
     $json_str = substr($response_->raw_body, 11, -1);
     $arr = json_decode($json_str, true);
     //        echo 'json_str is '.$json_str.PHP_EOL;
     //        echo 'current json_str length is '.strlen($json_str).PHP_EOL;
     if (strlen($json_str) > 0 && !is_null($arr) && isset($arr['commodityReviews'])) {
         //echo "commodity reviews arr count is ".count($arr['commodityReviews']).PHP_EOL;
         foreach ($arr['commodityReviews'] as $comment) {
             $content = $comment['content'];
             str_replace('\'', '', $content);
             str_replace('"', '', $content);
             str_replace(',', '', $content);
             $str .= $content . "\r\n";
         }
     } else {
         $has_more = false;
     }
     return $has_more;
 }
예제 #11
0
파일: Cas.php 프로젝트: PayIcam/shotgun
 public function authenticate($ticket, $service)
 {
     $r = Request::get($this->getValidateUrl($ticket, $service))->sendsXml()->timeoutIn($this->timeout)->send();
     $r->body = str_replace("\n", "", $r->body);
     try {
         $xml = new SimpleXMLElement($r->body);
     } catch (\Exception $e) {
         throw new \UnexpectedValueException("Return cannot be parsed : '{$r->body}'");
     }
     $namespaces = $xml->getNamespaces();
     $serviceResponse = $xml->children($namespaces['cas']);
     $user = $serviceResponse->authenticationSuccess->user;
     if ($user) {
         return (string) $user;
         // cast simplexmlelement to string
     } else {
         $authFailed = $serviceResponse->authenticationFailure;
         if ($authFailed) {
             $attributes = $authFailed->attributes();
             throw new \Exception((string) $attributes['code']);
         } else {
             throw new \Exception($r->body . " service:" . $service);
         }
     }
     // never reach there
 }
예제 #12
0
 /**
  * @param $route
  * @param $type
  * @param $data
  * @return array
  * @throws AcendaException
  * @throws Httpful\Exception\ConnectionErrorException
  */
 public function performRequest($route, $type, $data)
 {
     $httpful = Httpful\Request::init();
     if (!$this->bypass_ssl) {
         $httpful = $httpful->withStrictSSL();
     }
     $data_json = is_array($data) ? json_encode($data) : $data;
     $url = $this->store_url . (!empty($this->token['access_token']) ? "/api" . $route . "?access_token=" . $this->token['access_token'] : $route);
     switch (strtoupper($type)) {
         case 'GET':
             //Append the query.
             $url .= "&query=" . $data_json;
             $response = $httpful->get($url)->send();
             break;
         case 'PUT':
             $response = $httpful->put($url, $data_json)->sendsJson()->send();
             break;
         case 'POST':
             $response = $httpful->post($url, $data_json)->sendsJson()->send();
             break;
         default:
             throw new AcendaException('Verb ' . $type . ' Not Understood');
     }
     //Default in this switch is failure. All failures should fall through to default.
     switch ($response->code) {
         case 200:
         case 201:
             return $this->requestSuccess($response);
         default:
             return $this->requestFailure($response);
     }
 }
예제 #13
0
파일: Message.php 프로젝트: woldy/ddsdk
 /**
  * 根据详细参数发送企业消息
  * @Author   Woldy
  * @DateTime 2016-05-12T09:15:39+0800
  * @param    [type]                   $touser      [description]
  * @param    [type]                   $toparty     [description]
  * @param    [type]                   $content     [description]
  * @param    [type]                   $AgentID     [description]
  * @param    [type]                   $ACCESS_TOKEN [description]
  * @param    string                   $type        [description]
  * @return   [type]                                [description]
  */
 public static function sendMessage($touser, $toparty, $content, $AgentID, $ACCESS_TOKEN, $type = 'text')
 {
     //$content=iconv('GB2312', 'UTF-8', $content);
     //
     if ($type == 'text') {
         if (mb_detect_encoding($content, 'UTF-8') != 'UTF-8') {
             $content = iconv('GB2312', 'UTF-8', $content);
         }
         $param = array('touser' => $touser, 'toparty' => $toparty, 'agentid' => $AgentID, "msgtype" => "text", "text" => array("content" => $content));
         //var_dump(json_encode($param));
         //exit;
         $response = Request::post('https://oapi.dingtalk.com/message/send?access_token=' . $ACCESS_TOKEN)->body(json_encode($param))->sends('application/json')->send();
         if ($response->hasErrors()) {
             var_dump($response);
             exit;
         }
         if (!is_object($response->body)) {
             $response->body = json_decode($response->body);
         }
         if ($response->body->errcode != 0) {
             var_dump($response->body);
             exit;
         }
         echo 'send ok';
         exit;
     }
 }
예제 #14
0
    /**
     * 执行http发送请求
     *
     * @throws \Httpful\Exception\ConnectionErrorException
     */
    protected function sendRequest()
    {
        !$this->httpful and $this->httpful = Request::init($this->method);
        $payload = '';
        if (in_array($this->httpful->method, ['POST', 'PUT'])) {
            $payload = $this->makePayload();
        }
        $uri = $this->account->getSchemeHost() . $this->requestResource;
        $this->urlParams and $uri .= '?' . http_build_query($this->urlParams) and $this->requestResource .= '?' . http_build_query($this->urlParams);
        $this->httpful->uri($uri);
        $this->httpful->addHeader('Content-Length', strlen($payload));
        $this->httpful->addHeader('Content-MD5', base64_encode(md5($payload)));
        $this->httpful->addHeader('Content-Type', 'text/xml;utf-8');
        $this->httpful->addHeader('Date', date('D, d M Y H:i:s', time()) . ' GMT');
        $this->httpful->addHeader('Host', $this->account->getHost());
        $this->makeSpecificHeaders();
        $this->httpful->body($payload);
        $this->httpful->addHeader('Authorization', $this->makeSignature());
        try {
            return $this->httpful->send();
        } catch (\Exception $e) {
            return new Response(sprintf(<<<EOF
<?xml version="1.0"?>
<Error xmlns="http://mqs.aliyuncs.com/doc/v1">
  <Code>%s</Code>
  <Message>%s</Message>
  <RequestId>0</RequestId>
  <HostId>%s</HostId>
</Error>

EOF
, $e->getCode(), $e->getMessage() . '; FILE: ' . $e->getFile() . '; LINE: ' . $e->getLine(), $this->account->getSchemeHost()), "HTTP/1.1 400 OK\r\nServer: MOCK-SERVER\r\nContent-Type: text/xml;charset=utf-8\r\nx-mqs-request-id: 0", $this->httpful);
        }
    }
예제 #15
0
파일: Addic7ed.php 프로젝트: kipelovets/rss
 public function fetchOriginal($showTitle, $season, $episode)
 {
     $episodeLink = $this->fetchEpisodeLink($showTitle, $season, $episode);
     $doc = Request::get($episodeLink)->send()->body;
     $dom = new DOMDocument('1.0', 'utf-8');
     @$dom->loadHTML($doc);
     $xp = new DOMXPath($dom);
     $links = $xp->query('//strong[text()="original"]');
     if ($links->length == 0) {
         $links = $xp->query('//table[@class="tabel95"]//td[@class="language"][contains(text(),"English")]');
         if ($links->length == 0) {
             echo "Subtitle not found: {$episodeLink}\n";
             return;
         } else {
             $tds = $links;
             $links = [];
             foreach ($tds as $td) {
                 $linkNode = $xp->query('../td/a[@class="buttonDownload"]/strong', $td)->item(0);
                 if ($linkNode) {
                     $links[] = $linkNode;
                 }
             }
         }
     }
     foreach ($links as $linkNode) {
         $link = $linkNode->parentNode->getAttribute('href');
         $subLink = "http://www.addic7ed.com{$link}";
         $response = Request::get($subLink)->addHeader('Referer', $episodeLink)->send();
         $disp = $response->headers['Content-Disposition'];
         preg_match('/filename="([^"]+)"/', $disp, $m);
         return ['filename' => $m[1], 'body' => $response->body];
     }
 }
예제 #16
0
function getNewsObjects()
{
    //CACHING ENABLED: The server will only fetch news again if the cache has expired. Set expiry values in caching.php
    /*************** CACHE **************/
    $newsCacheName = 'newscache';
    $responsejson = null;
    $cacheExpired = is_null(checkCache($newsCacheName));
    $noCache = !is_null($_GET["nocache"]);
    ////////////////////////
    if ($cacheExpired || $noCache) {
        $uri = "http://api.nytimes.com/svc/news/v3/content/all/all.json?api-key={$newsapikey}";
        $rawresponsejson = \Httpful\Request::get($uri)->send();
        $responsejson = $rawresponsejson . raw_body;
        setCacheVal($newsCacheName, $responsejson);
        if ($debug) {
            echo "Fetched.";
        }
    } else {
        if ($debug) {
            echo "From cache.";
        }
        $responsejson = getCacheVal($newsCacheName);
    }
    return parseArticleObjectsFromJson($responsejson);
}
예제 #17
0
function getPhotos($category, $posts)
{
    $is_highlights = !is_array($posts);
    $data = !$is_highlights ? $posts : [];
    $url = 'http://' . $_SERVER['SERVER_NAME'] . '/' . 'cms/wp-json/posts?filter[posts_per_page]=-1&filter[order]=desc&filter[orderby]=post_date' . ($is_highlights ? '&filter[category_name]=destaque' : null);
    $response = \Httpful\Request::get($url)->send();
    $catId = get_cat_ID($category);
    foreach ($response->body as $key => $post) {
        $image_src = getImage($post->content);
        $attachment_id = pn_get_attachment_id_from_url($image_src);
        $image_large_src = wp_get_attachment_image_src($attachment_id, 'large');
        if (!$is_highlights && !isHighgligthCategory($catId, $post->terms->category)) {
            if ($image_src) {
                array_push($data, array('id' => $post->ID, 'title' => $post->title, 'image_src' => getImage($post->content), 'image_large_src' => $image_large_src[0]));
            }
        } else {
            if ($is_highlights && isHighgligthCategory($catId, $post->terms->category)) {
                if ($image_src) {
                    array_push($data, array('id' => $post->ID, 'title' => $post->title, 'image_src' => getImage($post->content), 'image_large_src' => $image_large_src[0]));
                }
            }
        }
    }
    return $data;
}
예제 #18
0
 private function getResponse($url)
 {
     $response = \Httpful\Request::get($url)->send();
     $responseraw = $response->raw_body;
     $result = json_decode($responseraw, true);
     return $result;
 }
예제 #19
0
파일: Hipchat.php 프로젝트: awoyele/omc
 /**
  * Send the HipChat message.
  *
  * @return void
  */
 public function send()
 {
     $message = $this->message ?: ucwords($this->getSystemUser()) . ' ran the [' . $this->task . '] task.';
     $format = $message != strip_tags($message) ? 'html' : 'text';
     $payload = ['auth_token' => $this->token, 'room_id' => $this->room, 'from' => $this->from, 'message' => $message, 'message_format' => $format, 'notify' => 1, 'color' => $this->color];
     Request::get('https://api.hipchat.com/v1/rooms/message?' . http_build_query($payload))->send();
 }
예제 #20
0
 /**
  * @before
  */
 public function initializeTestFiles()
 {
     // Ensure we have the Pony.fm test files
     if (!static::$initializedFiles) {
         Storage::disk('local')->makeDirectory('test-files');
         $storage = Storage::disk('testing');
         // To add new test files, upload them to poniverse.net/files
         // and add them here with their last-modified date as a Unix
         // timestamp.
         $files = ['ponyfm-test.flac' => 1450965707, 'ponyfm-transparent-cover-art.png' => 1451211579];
         foreach ($files as $filename => $lastModifiedTimestamp) {
             if (!$storage->has($filename) || $storage->lastModified($filename) < $lastModifiedTimestamp) {
                 echo "Downloading test file: {$filename}..." . PHP_EOL;
                 $testFileUrl = "https://poniverse.net/files/ponyfm-test-files/{$filename}";
                 $data = \Httpful\Request::getQuick($testFileUrl);
                 if ($data->code === 200) {
                     $storage->put($filename, $data->body);
                 } else {
                     $this->fail("A necessary test file was unavailable: {$testFileUrl}");
                 }
             }
         }
         // Delete any unnecessary test files
         foreach ($storage->allFiles() as $filename) {
             if (!isset($files[$filename])) {
                 $storage->delete($filename);
             }
         }
         static::$initializedFiles = true;
     }
 }
 public function callApi($requestUrl)
 {
     $requestUrl = $this->baseUrl . $this->lang . $this->apiUrl . $requestUrl;
     $response = \Httpful\Request::get($requestUrl)->expectsJson()->send();
     $transform = json_encode($response->body);
     $content = json_decode($transform, true);
     return $content;
 }
예제 #22
0
 protected function delete($uri, array $params = null)
 {
     if (!is_null($params)) {
         $params = self::clean_array($params);
         return self::process_response(Request::delete(self::$base_uri . $uri . '?' . http_build_query($params))->send());
     }
     return self::process_response(Request::delete(self::$base_uri . $uri)->send());
 }
예제 #23
0
 /**
  * Calls API and returns its response (or null if code != 200)
  * @param $uri
  * @return array|null|object|string
  */
 private function doRequest($uri)
 {
     $response = \Httpful\Request::get($uri)->authenticateWith($this->apiLogin, $this->apiPassword)->expects('json')->send();
     if ($response->code != Response::HTTP_OK) {
         return null;
     }
     return $response->body;
 }
예제 #24
0
 /**
  * Returns the query in the response format requested.
  * (Ex: json, xml)
  *
  * @return mixed
  *    Query response
  */
 public function query()
 {
     // echo "\n YOUR QUERY \n" . $this->__toString() . "\n END QUERY \n";
     $request = Request::get($this->__toString())->send();
     $response = $request->raw_body;
     var_dump($request);
     return $response;
 }
예제 #25
0
 /**
  * Post Request
  *
  * @param string $uri
  * @return \Httpful\Response
  */
 public function post($uri, $params = array())
 {
     if ($params) {
         $uri .= "?" . http_build_query($params);
     }
     $this->output("POST : " . $uri);
     return new \Httpful\Response("", "HTTP/1.1 200 OK\r\n", \Httpful\Request::init());
 }
예제 #26
0
 /**
  * Reset passbolt installation
  * @return bool
  */
 public static function resetDatabase($url, $dummy = 'seleniumtests')
 {
     $response = \Httpful\Request::get($url . '/seleniumTests/resetInstance/' . $dummy)->send();
     $seeCreated = preg_match('/created/', $response->body);
     sleep(2);
     // Wait for database to be imported (no visible output).
     return $seeCreated;
 }
예제 #27
0
 /**
  * Send Request to API-Server
  * @return self
  */
 public function send()
 {
     if (is_null($this->what) && is_null($this->where)) {
         throw new Exception("No Searchparameter given");
     }
     $uri = $this->getUri();
     $response = Request::get($uri)->expectsXml()->send();
     return new Response($response);
 }
예제 #28
0
 /**
  * @param $client_id Developer ID, usually in form of user@domain.com
  * @param $client_secret Developer key provided by Acenda.
  * @param $store_url The URL of the store we are working with.
  * @param $plugin_name Friendly name for localeconv(oid)gs etc. I don't think this is implemented.
  * @param $bypass_ssl Rather the SSL verification should be strict or not.
  * @throws AcendaException
  */
 public function __construct($client_id, $client_secret, $store_name, $bypass_ssl = false)
 {
     $this->httpful = Httpful\Request::init();
     if (!$bypass_ssl) {
         $this->httpful = $this->httpful->withStrictSSL();
     }
     Authentication::init($client_id, $client_secret, $this->httpful);
     $this->generateStoreUrl($store_name);
 }
예제 #29
0
파일: SSOService.php 프로젝트: TJUSSE/ICSS
 /**
  * 获取一个学生的基本信息
  *
  * @param $token
  * @return array|null
  */
 public function getStudentInfo($token)
 {
     $response = \Httpful\Request::get($this->ssoAPIHost . '/info/student?sessionid=' . urlencode($token))->expectsJson()->send();
     // 包含 msg,则代表失败
     if (!$response->body->ok) {
         return null;
     }
     return (array) $response->body->info;
 }
예제 #30
-5
파일: Http.php 프로젝트: dongww/web-monitor
 /**
  * @param Request $request
  *
  * @return HttpServer
  */
 public function getHttpServer(Request $request)
 {
     $url = $request->getUri();
     switch ($request->getMethod()) {
         case Request::METHOD_POST:
             $httpServer = HttpServer::post($url);
             break;
         case Request::METHOD_PUT:
             $httpServer = HttpServer::put($url);
             break;
         case Request::METHOD_DELETE:
             $httpServer = HttpServer::delete($url);
             break;
         default:
             $httpServer = HttpServer::get($url);
             break;
     }
     if ($request->headers) {
         $httpServer->addHeaders($request->headers->all());
     }
     if ($request->getUser()) {
         $httpServer->authenticateWith($request->getUser(), $request->getPassword());
     }
     if ($request->getContent()) {
         $httpServer->body($request->getContent());
     }
     return $httpServer;
 }