function getRss($url, $port, $timeout) { $results = array('rss' => array(), 'error' => ""); try { $request = new HTTP_Request2($url, HTTP_Request2::METHOD_POST); $request->setConfig("connect_timeout", $timeout); $request->setConfig("timeout", $timeout); $request->setHeader("user-agent", $_SERVER['HTTP_USER_AGENT']); $response = $request->send(); if ($response->getStatus() == 200) { // パース $body = $response->getBody(); if (substr($body, 0, 5) == "<?xml") { $results['rss'] = new MagpieRSS($body, "UTF-8"); } else { throw new Exception("Not xml data"); } } else { throw new Exception("Server returned status: " . $response->getStatus()); } } catch (HTTP_Request2_Exception $e) { $results['error'] = $e->getMessage(); } catch (Exception $e) { $results['error'] = $e->getMessage(); } // タイムアウト戻し ini_set('default_socket_timeout', $oldtimeout); return $results; }
/** * * @param TW2MV_Configure */ public function __construct($config) { try { $this->http = new HTTP_Request2(); $this->http->setConfig('ssl_verify_peer', false); } catch (Exception $e) { debug($e->getMessage()); } $this->config = $config; }
private function __construct() { // sanity check $siteUrl = get_option('siteurl'); $layoutUrl = DAIQUIRI_URL . '/core/layout/'; if (strpos($layoutUrl, $siteUrl) !== false) { echo '<h1>Error with theme</h1><p>Layout URL is below CMS URL.</p>'; die(0); } // construct request require_once 'HTTP/Request2.php'; $req = new HTTP_Request2($layoutUrl); $req->setConfig(array('ssl_verify_peer' => false, 'connect_timeout' => 2, 'timeout' => 3)); $req->setMethod('GET'); $req->addCookie("PHPSESSID", $_COOKIE["PHPSESSID"]); try { $response = $req->send(); if (200 != $response->getStatus()) { echo '<h1>Error with theme</h1><p>HTTP request status != 200.</p>'; die(0); } } catch (HTTP_Request2_Exception $e) { echo '<h1>Error with theme</h1><p>Error with HTTP request.</p>'; die(0); } $body = explode('<!-- content -->', $response->getBody()); if (count($body) == 2) { $this->_header = $body[0]; $this->_footer = $body[1]; } else { echo '<h1>Error with theme</h1><p>Malformatted layout.</p>'; die(0); } }
private function request($method, $path, $params = array()) { $url = $this->api . rtrim($path, '/') . '/'; if (!strcmp($method, "POST")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_POST); $req->setHeader('Content-type: application/json'); if ($params) { $req->setBody(json_encode($params)); } } else { if (!strcmp($method, "GET")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $url = $req->getUrl(); $url->setQueryVariables($params); } else { if (!strcmp($method, "DELETE")) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_DELETE); $url = $req->getUrl(); $url->setQueryVariables($params); } } } $req->setAdapter('curl'); $req->setConfig(array('timeout' => 30)); $req->setAuth($this->auth_id, $this->auth_token, HTTP_Request2::AUTH_BASIC); $req->setHeader(array('Connection' => 'close', 'User-Agent' => 'PHPPlivo')); $r = $req->send(); $status = $r->getStatus(); $body = $r->getbody(); $response = json_decode($body, true); return array("status" => $status, "response" => $response); }
function twipic($f, $a, $b, $m) { $twitpic_api = ""; $consumer_key = ""; $consumer_secret = ""; $access_token = $a; $access_token_secret = $b; $imagepath = $f; $message = $me; $consumer = new HTTP_OAuth_Consumer($consumer_key, $consumer_secret); $consumer->setToken($access_token); $consumer->setTokenSecret($access_token_secret); $http_request = new HTTP_Request2(); $http_request->setConfig('ssl_verify_peer', false); $consumer_request = new HTTP_OAuth_Consumer_Request(); $consumer_request->accept($http_request); $consumer->accept($consumer_request); $resp = $consumer->sendRequest('https://api.twitter.com/1.1/account/verify_credentials.json', array(), HTTP_Request2::METHOD_GET); $headers = $consumer->getLastRequest()->getHeaders(); $http_request->setHeader('X-Auth-Service-Provider', 'https://api.twitter.com/1.1/account/verify_credentials.json'); $http_request->setHeader('X-Verify-Credentials-Authorization', $headers['authorization']); $http_request->setUrl('http://api.twitpic.com/2/upload.json'); $http_request->setMethod(HTTP_Request2::METHOD_POST); $http_request->addPostParameter('key', $twitpic_api); $http_request->addPostParameter('message', $m); $http_request->addUpload('media', $imagepath); $resp = $http_request->send(); $body = $resp->getBody(); $body = json_decode($body, true); return $body; }
public function testBug17826() { $adapter = new HTTP_Request2_Adapter_Socket(); $request1 = new HTTP_Request2($this->baseUrl . 'redirects.php?redirects=2'); $request1->setConfig(array('follow_redirects' => true, 'max_redirects' => 3))->setAdapter($adapter)->send(); $request2 = new HTTP_Request2($this->baseUrl . 'redirects.php?redirects=2'); $request2->setConfig(array('follow_redirects' => true, 'max_redirects' => 3))->setAdapter($adapter)->send(); }
protected function getRequest() { if (!$this->request instanceof HTTP_Request2) { $this->request = new HTTP_Request2(); $this->request->setConfig(array('connect_timeout' => 1, 'timeout' => 3)); } return clone $this->request; }
/** * Creates a HTTP client if none is set. * * @return \HTTP_Request2 */ public function getClient() { if (false === $this->client instanceof \HTTP_Request2) { $this->client = new \HTTP_Request2(); $this->client->setConfig(array('adapter' => 'HTTP_Request2_Adapter_Curl', 'timeout' => 3, 'max_redirects' => 1)); } $this->client->setAuth($this->publicKey, $this->privateKey); return $this->client; }
public function testTimeout() { $this->request->setConfig('timeout', 2); try { $this->request->send(); $this->fail('Expected HTTP_Request2_Exception was not thrown'); } catch (HTTP_Request2_Exception $e) { } }
public static function update($userid) { global $HTTP_CONFIG; $username = Token::get(self::name, $userid); $request = new HTTP_Request2('https://hacker-news.firebaseio.com/v0/user/' . $username . '.json'); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $karma = json_decode($response)->karma; Score::update(self::name, $userid, $karma); }
public static function update($userid) { global $HTTP_CONFIG; $username = Token::get(self::name, $userid); $request = new HTTP_Request2('http://open.dapper.net/transform.php?dappName=CodeChefProblemsSolved&transformer=JSON&v_username=' . $username); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $score = json_decode($response)->fields->solved[32]->value; Score::update(self::name, $userid, $score); }
public function testTimeoutInRequest() { $this->request->setConfig('timeout', 2)->setUrl($this->baseUrl . 'postparameters.php')->setBody(new SlowpokeBody(array('foo' => 'some value'), array())); try { $this->request->send(); $this->fail('Expected HTTP_Request2_MessageException was not thrown'); } catch (HTTP_Request2_MessageException $e) { $this->assertEquals(HTTP_Request2_Exception::TIMEOUT, $e->getCode()); } }
public static function update($userid) { global $HTTP_CONFIG; $lastFMUsername = Token::get(self::name, $userid); $request = new HTTP_Request2('http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user='******'&api_key=' . LASTFM_APP_ID . '&format=json'); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $playcount = trim(json_decode($response)->user->playcount); Score::update(self::name, $userid, $playcount); //Update in database }
public static function update($userid) { global $HTTP_CONFIG; $twitterScreenName = Token::get(self::name, $userid); $request = new HTTP_Request2('https://api.twitter.com/1/users/show.json?screen_name=' . $twitterScreenName); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $followers_count = json_decode($response)->followers_count; Score::update(self::name, $userid, $followers_count); //Update in database }
public static function update($userid) { global $HTTP_CONFIG; $id = Token::get(self::name, $userid); $request = new HTTP_Request2('https://api.stackexchange.com/2.1/users/' . $id . '?site=askubuntu&key=' . STACKEXCHANGE_KEY); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $reputation = json_decode($response)->items[0]->reputation; Score::update(self::name, $userid, $reputation); //Update in database }
/** * リソースリクエスト実行 * * リモートURLにアクセスしてRSSだったら配列に、 * そうでなかったらHTTP Body文字列をリソースとして扱います。 * * @return BEAR_Ro * @throws BEAR_Resource_Execute_Exception */ public function request() { $reqMethod = array(); $reqMethod[BEAR_Resource::METHOD_CREATE] = HTTP_Request2::METHOD_POST; $reqMethod[BEAR_Resource::METHOD_READ] = HTTP_Request2::METHOD_GET; $reqMethod[BEAR_Resource::METHOD_UPDATE] = HTTP_Request2::METHOD_PUT; $reqMethod[BEAR_Resource::METHOD_DELETE] = HTTP_Request2::METHOD_DELETE; assert(isset($reqMethod[$this->_config['method']])); try { // 引数以降省略可能 config で proxy とかも設定可能 $request = new HTTP_Request2($this->_config['uri'], $reqMethod[$this->_config['method']]); $request->setHeader("user-agent", 'BEAR/' . BEAR::VERSION); $request->setConfig("follow_redirects", true); if ($this->_config['method'] === BEAR_Resource::METHOD_CREATE || $this->_config['method'] === BEAR_Resource::METHOD_UPDATE) { foreach ($this->_config['values'] as $key => $value) { $request->addPostParameter($key, $value); } } $response = $request->send(); $code = $response->getStatus(); $headers = $response->getHeader(); if ($code == 200) { $body = $response->getBody(); } else { $info = array('code' => $code, 'headers' => $headers); throw $this->_exception($response->getBody(), $info); } } catch (HTTP_Request2_Exception $e) { throw $this->_exception($e->getMessage()); } catch (Exception $e) { throw $this->_exception($e->getMessage()); } $rss = new XML_RSS($body, 'utf-8', 'utf-8'); PEAR::setErrorHandling(PEAR_ERROR_RETURN); // @todo Panda::setPearErrorHandling(仮称)に変更しエラーを画面化しないようにする $rss->parse(); $items = $rss->getItems(); if (is_array($items) && count($items) > 0) { $body = $items; $headers = $rss->getChannelInfo(); $headers['type'] = 'rss'; } else { $headers['type'] = 'string'; $body = array($body); } // UTF-8に $encode = mb_convert_variables('UTF-8', 'auto', $body); $ro = BEAR::factory('BEAR_Ro')->setBody($body)->setHeaders($headers); /* @var $ro BEAR_Ro */ PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('Panda', 'onPearError')); return $ro; }
public static function update($userid) { global $HTTP_CONFIG; $username = Token::get(self::name, $userid); //More information at http://geekraj.com/wordpress/?p=278 //see http://geekraj.com/euler/euler.js $request = new HTTP_Request2('http://www.geekraj.com/euler/getscore.php?id=' . $username); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $score = json_decode(str_replace("'", '"', substr($response, 12, -2)))->score; $score = substr($score, 7); Score::update(self::name, $userid, $score); }
public function testUploadArray() { $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST); $body = $req->addUpload('upload', array(array(dirname(dirname(__FILE__)) . '/_files/plaintext.txt', 'bio.txt', 'text/plain'), array(fopen(dirname(dirname(__FILE__)) . '/_files/empty.gif', 'rb'), 'photo.gif', 'image/gif')))->getBody(); $asString = $body->__toString(); $this->assertContains(file_get_contents(dirname(dirname(__FILE__)) . '/_files/empty.gif'), $asString); $this->assertContains('name="upload[0]"; filename="bio.txt"', $asString); $this->assertContains('name="upload[1]"; filename="photo.gif"', $asString); $body2 = $req->setConfig(array('use_brackets' => false))->getBody(); $asString = $body2->__toString(); $this->assertContains('name="upload"; filename="bio.txt"', $asString); $this->assertContains('name="upload"; filename="photo.gif"', $asString); }
public static function requestToPostMethod($argURL, $argParams = NULL, $argFiles = NULL, $argTimeOut = 60) { $HttpRequestObj = new HTTP_Request2(); $urls = parse_url($argURL); if (isset($urls["user"]) && isset($urls["pass"])) { $HttpRequestObj->setAuth($urls["user"], $urls["pass"]); } if (isset($urls["port"])) { $url = $urls["scheme"] . '://' . $urls["host"] . ':' . $urls["port"]; } else { $url = $urls["scheme"] . '://' . $urls["host"]; } if (isset($urls["path"])) { $url .= $urls["path"]; } $HttpRequestObj->setUrl($url); $HttpRequestObj->setMethod(HTTP_Request2::METHOD_POST); if ('https' === $urls["scheme"]) { $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE)); } else { $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut)); } if (is_array($argParams)) { foreach ($argParams as $key => $value) { $HttpRequestObj->addPostParameter($key, $value); } } // ファイルをアップロードする場合 if (is_array($argFiles)) { foreach ($argFiles as $key => $value) { $HttpRequestObj->addUpload($key, $value); } } // リクエストを送信 $response = $HttpRequestObj->send(); // レスポンスのボディ部を表示 return $response; }
public static function update($userid) { global $HTTP_CONFIG; $request = new HTTP_Request2('http://gitscore.com/user/' . $userid . '/calculate'); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $score = json_decode($response)->scores->total; if (!$score) { echo "User not in gitscore, try a little later\n"; return false; } Score::update(self::name, $userid, $score); //Update in database }
public function preResolve(\Cx\Core\Routing\Url $url) { if ($this->cx->getMode() != \Cx\Core\Core\Controller\Cx::MODE_FRONTEND) { return; } $em = $this->cx->getDb()->getEntityManager(); $rewriteRuleRepo = $em->getRepository($this->getNamespace() . '\\Model\\Entity\\RewriteRule'); $rewriteRules = $rewriteRuleRepo->findAll(array(), array('order' => 'asc')); $last = false; $originalUrl = clone $url; foreach ($rewriteRules as $rewriteRule) { try { $url = $rewriteRule->resolve($url, $last); } catch (\Exception $e) { // This is thrown if the regex of the rule is not valid } if ($last) { break; } } if ($originalUrl->toString() != $url->toString()) { if ($rewriteRule->getRewriteStatusCode() != \Cx\Core\Routing\Model\Entity\RewriteRule::REDIRECTION_TYPE_INTERN) { $headers = array('Location' => $url->toString()); if ($rewriteRule->getRewriteStatusCode() == 301) { array_push($headers, $_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently'); } $this->getComponent('Cache')->writeCacheFileForRequest(null, $headers, ''); \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $url->toString(), true, $rewriteRule->getRewriteStatusCode()); die; } try { \DBG::log('Fetching content from ' . $url->toString()); $request = new \HTTP_Request2($url->toString(), \HTTP_Request2::METHOD_GET); $request->setConfig(array('follow_redirects' => true)); $response = $request->send(); $content = $response->getBody(); foreach ($response->getHeader() as $key => $value) { if (in_array($key, array('content-encoding', 'transfer-encoding'))) { continue; } \Cx\Core\Csrf\Controller\Csrf::header($key . ':' . $value); } $continue = false; die($content); } catch (\HTTP_Request2_Exception $e) { \DBG::dump($e); } } }
public static function update($userid) { global $HTTP_CONFIG; $id = Token::get(self::name, $userid); $request = new HTTP_Request2('http://api.klout.com/v2/identity.json/twitter?screenName=' . $id . '&key=' . KLOUT_APP_KEY); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $id = json_decode($response)->id; $request = new HTTP_Request2('http://api.klout.com/v2/user.json/' . $id . '/score?key=' . KLOUT_APP_KEY); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); $score = (int) json_decode($response)->score; Score::update(self::name, $userid, $score); //Update in database }
public static function update($userid) { global $HTTP_CONFIG; $username = Token::get(self::name, $userid); $request = new HTTP_Request2('http://open.dapper.net/transform.php?dappName=ScoreFromSpoj&transformer=JSON&v_username='******' '); $score = substr($score, 1, $spacePosition - 1); Score::update(self::name, $userid, $score); }
protected static function post($url, $content) { $request = new HTTP_Request2($url); $request->setMethod(HTTP_Request2::METHOD_POST); foreach ($content as $name => $val) { $request->addPostParameter($name, $val); } $request->setConfig(array('ssl_verify_peer' => false)); try { $response = $request->send(); $body = $response->getBody(); return $body; } catch (HTTP_Request2_Exception $e) { return false; } }
public static function callback() { global $HTTP_CONFIG; //exchange the code you get for a access_token $code = $_GET['code']; $request = new HTTP_Request2(self::ACCESS_TOKEN_URL); $request->setMethod(HTTP_Request2::METHOD_POST); $request->setConfig($HTTP_CONFIG); $request->addPostParameter(['client_id' => GITHUB_APP_ID, 'client_secret' => GITHUB_APP_SECRET, 'code' => $code]); $request->setHeader('Accept', 'application/json'); $response = $request->send(); $response = json_decode($response->getBody()); $access_token = $response->access_token; //Use this access token to get user details $request = new HTTP_Request2(self::USER_URL . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG); $response = $request->send()->getBody(); $userid = json_decode($response)->login; //get the userid //If such a user already exists in the database //Just log him in and don't touch the access_token $already_present_token = Token::get('github', $userid); if ($already_present_token) { $_SESSION['userid'] = $userid; redirect_to('/'); } if (defined('GITHUB_ORGANIZATION')) { // perform the organization check $request = new HTTP_Request2(json_decode($response)->organizations_url . '?access_token=' . $access_token, HTTP_Request2::METHOD_GET, $HTTP_CONFIG); $response = $request->send()->getBody(); //List of organizations $organizations_list = array_map(function ($repo) { return $repo->login; }, json_decode($response)); if (in_array(GITHUB_ORGANIZATION, $organizations_list)) { $_SESSION['userid'] = $userid; Token::add('github', $userid, $access_token); } else { throw new Exception('You are not in the listed members.'); } } else { $_SESSION['userid'] = $userid; Token::add('github', $userid, $access_token); } redirect_to('/'); }
/** * 記事を投稿する. * * @param string $title 記事タイトル * @param string $text 記事本文 * @param string $category 記事カテゴリ * @return string $res 結果 */ public function postArticle($title, $text, $category) { try { $req = new HTTP_Request2(); $req->setUrl(self::ROOT_END_POINT . $this->liveDoorId . "/" . self::END_POINT_TYPE_ARTICLE); $req->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false)); $req->setMethod(HTTP_Request2::METHOD_POST); $req->setAuth($this->liveDoorId, $this->atomPubPassword); $req->setBody($this->createBody($title, $text, $category)); $req->setHeader('Expect', ''); $res = $req->send(); } catch (HTTP_Request2_Exception $e) { die($e->getMessage()); } catch (Exception $e) { die($e->getMessage()); } return $res; }
public static function callback() { global $HTTP_CONFIG; //Check state for csrf attack if ($_SESSION['state'] != $_GET['state']) { throw new Exception('Invalid Request. Please try again.'); } //Get the access code $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/login/facebook/callback'; $token_url = 'https://graph.facebook.com/oauth/access_token?' . 'client_id=' . FACEBOOK_APP_ID . '&redirect_uri=' . urlencode($redirect_uri) . '&client_secret=' . FACEBOOK_APP_SECRET . '&code=' . $_GET['code']; //Send the request $request = new HTTP_Request2($token_url); $request->setConfig($HTTP_CONFIG); $response = $request->send()->getBody(); parse_str($response, $params); //Save it inside as an access_token Token::add(self::name, $_SESSION['userid'], $params['access_token']); redirect_to('/'); }
/** * Call the places Api with the url from builQuery() and handle the response */ private function makeApiRequest() { $this->buildQuery(); $request = new \HTTP_Request2($this->query, \HTTP_Request2::METHOD_GET); $request->setConfig(array('ssl_verify_peer' => false)); try { $response = $request->send(); $this->responseCode = $response->getStatus(); $this->responseBody = $response->getBody(); if ((int) $this->responseCode !== 200) { $this->responseBody = json_encode(array("error" => "Sorry. We encountered a " . $this->responseCode . " code from the maps api")); } $this->validateJsonResponseData(); } catch (Exception $e) { // We wouldn't usually expose this error to the user // log $e->getMessage() $this->responseCode = 500; $this->responseBody = json_encode(array('error' => 'An internal error occurrred. Please try again.')); } }
private function http2_request($method, $path, $params) { $url = $this->api . $path; $http_method = \HTTP_Request2::METHOD_POST; if (!strcmp($method, "GET")) { $http_method = \HTTP_Request2::METHOD_GET; } else { if (!strcmp($method, "DELETE")) { $http_method = \HTTP_Request2::METHOD_DELETE; } } $req = new \HTTP_Request2($url, $http_method); if ($http_method === \HTTP_Request2::METHOD_POST && $params) { $req->setBody(json_encode($params)); } $req->setAdapter('curl'); $req->setConfig(array('timeout' => 30, 'ssl_verify_peer' => FALSE)); $req->setHeader(array('Authorization' => $this->auth_token, 'Connection' => 'close', 'User-Agent' => 'CheckMobi/http2_request', 'Content-type' => 'application/json')); $r = $req->send(); $status = $r->getStatus(); $body = $r->getbody(); $response = json_decode($body, true); return array("status" => $status, "response" => $response); }
/** * Get HTTP request response header string * * @param string $url target URL * @return string * @author Naoki Sawada */ private function getHttpResponseHeader($url) { if (function_exists('curl_exec')) { $c = curl_init(); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); curl_setopt($c, CURLOPT_CUSTOMREQUEST, 'HEAD'); curl_setopt($c, CURLOPT_HEADER, 1); curl_setopt($c, CURLOPT_NOBODY, true); curl_setopt($c, CURLOPT_URL, $url); $res = curl_exec($c); } else { require_once 'HTTP/Request2.php'; try { $request2 = new HTTP_Request2(); $request2->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false)); $request2->setUrl($url); $request2->setMethod(HTTP_Request2::METHOD_HEAD); $result = $request2->send(); $res = array(); $res[] = 'HTTP/' . $result->getVersion() . ' ' . $result->getStatus() . ' ' . $result->getReasonPhrase(); foreach ($result->getHeader() as $key => $val) { $res[] = $key . ': ' . $val; } $res = join("\r\n", $res); } catch (HTTP_Request2_Exception $e) { $res = ''; } catch (Exception $e) { $res = ''; } } return $res; }