/** * Test that the default privacy setting is used when an existing * bookmark is updated with edit.php. */ public function testDefaultPrivacyEdit() { $this->setUnittestConfig(array('defaults' => array('privacy' => 2))); list($req, $uId) = $this->getLoggedInRequest('?unittestMode=1'); $cookies = $req->getCookieJar(); $req->setMethod(HTTP_Request2::METHOD_POST); $req->addPostParameter('url', 'http://www.example.org/testdefaultprivacyposts_edit'); $req->addPostParameter('description', 'Test bookmark 2 for default privacy.'); $req->addPostParameter('status', '0'); $res = $req->send(); $this->assertEquals(200, $res->getStatus(), 'Adding bookmark failed: ' . $res->getBody()); $bms = $this->bs->getBookmarks(0, null, $uId); $bm = reset($bms['bookmarks']); $bmId = $bm['bId']; $reqUrl = $GLOBALS['unittestUrl'] . 'edit.php/' . $bmId . '?unittestMode=1'; $req2 = new HTTP_Request2($reqUrl, HTTP_Request2::METHOD_POST); $req2->setCookieJar($cookies); $req2->addPostParameter('address', 'http://www.example.org/testdefaultprivacyposts_edit'); $req2->addPostParameter('title', 'Test bookmark 2 for default privacy.'); $req2->addPostParameter('submitted', '1'); $res = $req2->send(); $this->assertEquals(302, $res->getStatus(), 'Editing bookmark failed'); $bm = $this->bs->getBookmark($bmId); $this->assertEquals('2', $bm['bStatus']); }
/** * GET Request * * @param $url * @param $datas * @return string */ public function get_request($url, $datas = array()) { $body = ''; try { $url2 = new Net_URL2($url); foreach ($datas as $key => $val) { $url2->setQueryVariable($key, mb_convert_encoding($val, $this->response_encoding, 'UTF-8'), true); } $this->http->setURL($url2); $this->http->setMethod(HTTP_Request2::METHOD_GET); if (!empty($this->cookies)) { foreach ($this->cookies as $cookie) { $this->http->addCookie($cookie['name'], $cookie['value']); } } $response = $this->http->send(); if (count($response->getCookies())) { $this->cookies = $response->getCookies(); } $body = mb_convert_encoding($response->getBody(), 'UTF-8', $this->response_encoding); } catch (Exception $e) { debug($e->getMessage()); } return $body; }
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 send_post_data($url, $data) { require_once 'HTTP/Request2.php'; $request = new HTTP_Request2($url); $request->setMethod(HTTP_Request2::METHOD_POST)->addPostParameter($data); return $request->send(); }
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); } }
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; }
public function erzData($zip = null, $type = null, $page = 1) { if ($type) { $url = 'http://openerz.herokuapp.com:80/api/calendar/' . $type . '.json'; } else { $url = 'http://openerz.herokuapp.com:80/api/calendar.json'; } //Http-request $request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET); $reqUrl = $request->getUrl(); $pageSize = 10; $reqUrl->setQueryVariable('limit', $pageSize); $offset = ($page - 1) * $pageSize; $reqUrl->setQueryVariable('offset', $offset); if ($zip) { $reqUrl->setQueryVariable('zip', $zip); } try { $response = $request->send(); // 200 ist für den Status ob ok ist 404 wäre zum Beispiel ein Fehler if ($response->getStatus() == 200) { return json_decode($response->getBody()); } } catch (HTTP_Request2_Exception $ex) { echo $ex; } return null; }
/** * Processes the reuqest through HTTP pipeline with passed $filters, * sends HTTP request to the wire and process the response in the HTTP pipeline. * * @param array $filters HTTP filters which will be applied to the request before * send and then applied to the response. * @param IUrl $url Request url. * * @throws WindowsAzure\Common\ServiceException * * @return string The response body */ public function send($filters, $url = null) { if (isset($url)) { $this->setUrl($url); $this->_request->setUrl($this->_requestUrl->getUrl()); } $contentLength = Resources::EMPTY_STRING; if (strtoupper($this->getMethod()) != Resources::HTTP_GET && strtoupper($this->getMethod()) != Resources::HTTP_DELETE && strtoupper($this->getMethod()) != Resources::HTTP_HEAD) { $contentLength = 0; if (!is_null($this->getBody())) { $contentLength = strlen($this->getBody()); } $this->_request->setHeader(Resources::CONTENT_LENGTH, $contentLength); } foreach ($filters as $filter) { $this->_request = $filter->handleRequest($this)->_request; } $this->_response = $this->_request->send(); $start = count($filters) - 1; for ($index = $start; $index >= 0; --$index) { $this->_response = $filters[$index]->handleResponse($this, $this->_response); } self::throwIfError($this->_response->getStatus(), $this->_response->getReasonPhrase(), $this->_response->getBody(), $this->_expectedStatusCodes); return $this->_response->getBody(); }
/** * さくら水産のランチ情報を取得する * * @return array | false */ public function fetchLunchMenus() { $menus = array(); $today = new DateTime(); $request = new HTTP_Request2(); $request->setMethod(HTTP_Request2::METHOD_GET); $request->setUrl(self::LUNCHMENU_URL); try { $response = $request->send(); if (200 == $response->getStatus()) { $dom = new DOMDocument(); @$dom->loadHTML($response->getBody()); $xml = simplexml_import_dom($dom); foreach ($xml->xpath('//table/tr') as $tr) { if (preg_match('/(\\d+)月(\\d+)日/', $tr->td[0]->div, $matches)) { $dateinfo = new DateTime(sprintf('%04d-%02d-%02d', $today->format('Y'), $matches[1], $matches[2])); $_menus = array(); foreach ($tr->td[1]->div->strong as $strong) { $_menus[] = (string) $strong; } $menus[$dateinfo->format('Y-m-d')] = $_menus; } } } } catch (HTTP_Request2_Exception $e) { // HTTP Error return false; } return $menus; }
public function getLanguagesFromTransifex() { $request = new HTTP_Request2('http://*****:*****@www.transifex.net/api/2/project/gaiaehr/resource/All/?details', HTTP_Request2::METHOD_GET); $r = $request->send()->getBody(); $r = json_decode($r, true); return array('langs' => $r['available_languages']); }
/** * Make the GET request * * @throws BuildException */ public function main() { if (!isset($this->url)) { throw new BuildException("Missing attribute 'url'"); } if (!isset($this->dir)) { throw new BuildException("Missing attribute 'dir'"); } $this->log("Fetching " . $this->url); $request = new HTTP_Request2($this->url); $response = $request->send(); if ($response->getStatus() != 200) { throw new BuildException("Request unsuccessfull. Response from server: " . $response->getStatus() . " " . $response->getReasonPhrase()); } $content = $response->getBody(); if ($this->filename) { $filename = $this->filename; } elseif ($disposition = $response->getHeader('content-disposition') && 0 == strpos($disposition, 'attachment') && preg_match('/filename="([^"]+)"/', $disposition, $m)) { $filename = basename($m[1]); } else { $filename = basename(parse_url($this->url, PHP_URL_PATH)); } if (!is_writable($this->dir)) { throw new BuildException("Cannot write to directory: " . $this->dir); } $filename = $this->dir . "/" . $filename; file_put_contents($filename, $content); $this->log("Contents from " . $this->url . " saved to {$filename}"); }
/** * Sends the request via HTTP_Request2 * * @return string The HTTP response body */ protected function sendRequest() { $this->getHTTPRequest2(); $this->response = $this->request->send(); if ($this->response->getStatus() !== 200) { throw new OpenID_Discover_Exception('Unable to connect to OpenID Provider.'); } return $this->response->getBody(); }
/** * Sends a request and returns a response * * @param CartRecover_Request $request * @return Cart_Recover_Response */ public function sendRequest(CartRecover_Request $request) { $this->client->setUrl($request->getUri()); $this->client->getUrl()->setQueryVariables($request->getParams()); $this->client->setMethod($request->getMethod()); $this->client->setHeader('Accept', 'application/json'); $this->response = $this->client->send(); if ($this->response->getHeader('Content-Type') != 'application/json') { throw new CartRecover_Exception_UnexpectedValueException("Unknown response format."); } $body = json_decode($this->response->getBody(), true); $response = new CartRecover_Response(); $response->setRawResponse($this->response->getBody()); $response->setBody($body); $response->setHeaders($this->response->getHeader()); $response->setStatus($this->response->getReasonPhrase(), $this->response->getStatus()); return $response; }
/** * Http request * * @param string $method * @param string $url * @param array $submit * @param string $formName * * @return HTTP_Request2_Response */ public function request($method, $url, array $submit = array(), $formName = 'form') { $this->request = new HTTP_Request2(); $url = new Net_URL2($url); $this->request->setMethod($method); if ($submit) { $submit = array_merge(array('_token' => '0dc59902014b6', '_qf__' . $formName => ''), $submit); } if ($submit && $method === 'POST') { $this->request->addPostParameter($submit); } if ($submit && $method === 'GET') { $url->setQueryVariables($submit); } $this->request->setUrl($url); $this->response = $this->request->send(); return $this; }
public function testRedirectsNonHTTP() { $this->request->setUrl($this->baseUrl . 'redirects.php?special=ftp')->setConfig(array('follow_redirects' => true)); try { $this->request->send(); $this->fail('Expected HTTP_Request2_Exception was not thrown'); } catch (HTTP_Request2_Exception $e) { } }
/** * @link http://pear.php.net/bugs/bug.php?id=19233 * @link http://pear.php.net/bugs/bug.php?id=15937 */ public function testPreventExpectHeader() { $fp = fopen(dirname(dirname(dirname(__FILE__))) . '/_files/bug_15305', 'rb'); $observer = new HeaderObserver(); $body = new HTTP_Request2_MultipartBody(array(), array('upload' => array('fp' => $fp, 'filename' => 'bug_15305', 'type' => 'application/octet-stream', 'size' => 16338))); $this->request->setMethod(HTTP_Request2::METHOD_POST)->setUrl($this->baseUrl . 'uploads.php')->setHeader('Expect', '')->setBody($body)->attach($observer); $response = $this->request->send(); $this->assertNotContains('Expect:', $observer->headers); $this->assertContains('upload bug_15305 application/octet-stream 16338', $response->getBody()); }
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); }
private function etcd_get($url, $base = false) { $base = $base === false ? $this->etcd_base : $base; /* Get some key from etcd */ $etcd_url = explode(",", getenv("ETCDCTL_PEERS"))[0] . "/v2/keys" . $base . $url; require_once 'HTTP/Request2.php'; $request = new HTTP_Request2($etcd_url, HTTP_Request2::METHOD_GET); $res = $request->send(); return json_decode($res->getBody()); }
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 send($mobile, $content) { $data = array('u' => $this->conf['u'], 'p' => md5($this->conf['p']), 'm' => $mobile, 'c' => $content . $this->conf['sign']); $http = new HTTP_Request2($this->conf['apiUriPrefix'] . 'sms', HTTP_Request2::METHOD_POST); $http->addPostParameter($data); $r = $http->send()->getBody(); if ($r != 0) { throw new Services_Sms_Exception($r); } return true; }
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; $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; $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 }
function getContents($url, $start = 0, $userAgent = null) { if ($start > 0) { $url .= "&start={$start}"; } $http = new HTTP_Request2($url); $http->setAdapter('curl'); if ($userAgent !== null) { $http->setHeader('User-Agent', $userAgent); } return $http->send(); }
public function send($mobile, $content) { $data = array('sname' => $this->conf['sname'], 'spwd' => $this->conf['spwd'], 'scorpid' => $this->conf['scorpid'], 'sprdid' => $this->conf['sprdid'], 'sdst' => $mobile, 'smsg' => $content . $this->conf['sign']); $http = new HTTP_Request2($this->conf['apiUriPrefix'] . '/g_Submit', HTTP_Request2::METHOD_POST); $http->addPostParameter($data); $r = $http->send()->getBody(); $tmp = $this->filter($r); if ($tmp['State'] != 0) { throw new Services_Sms_Exception($r); } return true; }
/** * Send an HTTP HEAD request for the given URL * * @param string $url URL to request * @param string $errorMessage error message, if any (on return) * @return int HTTP response code or 777 on error */ function doHeadRequest($url, &$errorMessage) { $req = new HTTP_Request2($url, HTTP_Request2::METHOD_HEAD); $req->setHeader('User-Agent', 'Geeklog/' . VERSION); try { $response = $req->send(); return $response->getStatus(); } catch (HTTP_Request2_Exception $e) { $errorMessage = $e->getMessage(); return 777; } }
/** * リソースリクエスト実行 * * リモート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); }
/** * Handles the response after sending. * * @param \HTTP_Request2 $request The HTTP request. * @param \HTTP_Request2_Response $response The HTTP response. * * @return \HTTP_Request2_Response */ public function handleResponse($request, $response) { for ($retryCount = 0;; $retryCount++) { $shouldRetry = $this->_retryPolicy->shouldRetry($retryCount, $response); if (!$shouldRetry) { return $response; } // Backoff for some time according to retry policy $backoffTime = $this->_retryPolicy->calculateBackoff($retryCount, $response); sleep($backoffTime * 0.001); $response = $request->send(array()); } }
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 }