/** * さくら水産のランチ情報を取得する * * @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; }
/** * 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(); }
/** * 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) { } }
/** * A helper function that retrieves external metadata and caches it * * @param string $url URL to fetch * @param string $id ID of the entity to fetch * @param string[] $headers Optional headers to add to the request * * @return string Metadata (typically XML) * @throws Exception */ protected function getExternalData($url, $id, $headers = []) { $cached = $this->db->uriCache->findOne(['_id' => $id, 'timestamp' => ['$gt' => new MongoDate(time() - $this->maxCacheAge)]]); if ($cached) { return $cached['data']; } if (is_null($this->request)) { $this->request = new HTTP_Request2($url, HTTP_Request2::METHOD_GET, ['ssl_verify_peer' => false, 'follow_redirects' => true]); $this->request->setHeader('Connection', 'Keep-Alive'); $this->request->setHeader('User-Agent', 'RecordManager'); } else { $this->request->setUrl($url); } if ($headers) { $this->request->setHeader($headers); } $response = null; for ($try = 1; $try <= $this->maxTries; $try++) { try { $response = $this->request->send(); } catch (Exception $e) { if ($try < $this->maxTries) { $this->log->log('getExternalData', "HTTP request for '{$url}' failed (" . $e->getMessage() . "), retrying in {$this->retryWait} seconds...", Logger::WARNING); sleep($this->retryWait); continue; } throw $e; } if ($try < $this->maxTries) { $code = $response->getStatus(); if ($code >= 300 && $code != 404) { $this->log->log('getExternalData', "HTTP request for '{$url}' failed ({$code}), retrying " . "in {$this->retryWait} seconds...", Logger::WARNING); sleep($this->retryWait); continue; } } break; } $code = is_null($response) ? 999 : $response->getStatus(); if ($code >= 300 && $code != 404) { throw new Exception("Enrichment failed to fetch '{$url}': {$code}"); } $data = $code != 404 ? $response->getBody() : ''; $this->db->uriCache->save(['_id' => $id, 'timestamp' => new MongoDate(), 'data' => $data]); return $data; }
/** * Fetches the HTML to be parsed * * @param string $url A valid URL to fetch * * @return string Return contents from URL (usually HTML) * * @throws Services_Mailman_Exception */ protected function fetch($url) { $url = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED); if (!$url) { throw new Services_Mailman_Exception('Invalid URL', Services_Mailman_Exception::INVALID_URL); } try { $this->request->setUrl($url); $this->request->setMethod('GET'); $html = $this->request->send()->getBody(); } catch (HTTP_Request2_Exception $e) { throw new Services_Mailman_Exception($e, Services_Mailman_Exception::HTML_FETCH); } if (strlen($html) > 5) { return $html; } throw new Services_Mailman_Exception('Could not fetch HTML', Services_Mailman_Exception::HTML_FETCH); }
/** * 記事を投稿する. * * @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; }
/** * Send a POST request to the specified URL with the specified payload. * @param string $url * @param string $data * @return string Remote data **/ public function sendPOST($url, $data = array()) { $data['_fake_status'] = '200'; // Send the actual request. $this->instance->setHeader('User-Agent', sprintf(Imgur::$user_agent, Imgur::$key)); $this->instance->setMethod('POST'); $this->instance->setUrl($url); foreach ($data as $k => $v) { $this->instance->addPostParameter($k, $v); } try { /** @var HTTP_Request2_Response */ $response = $this->instance->send(); return $response->getBody(); } catch (HTTP_Request2_Exception $e) { throw new Imgur_Exception("HTTP Request Failure", null, $e); } catch (Exception $e) { throw new Imgur_Exception("Unknown Failure during HTTP Request", null, $e); } }
/** * Loads the XRD file from the given URL. * Sets $react->error when loading fails * * @param string $url URL to fetch * * @return boolean True if loading data succeeded, false if not */ protected function loadXrd($url) { try { $react = new Net_WebFinger_Reaction(); $react->url = $url; $react->error = null; if ($this->httpClient !== null) { $this->httpClient->setUrl($url); $this->httpClient->setHeader('user-agent', 'PEAR Net_WebFinger', true); $this->httpClient->setHeader('accept', 'application/jrd+json, application/xrd+xml;q=0.9', true); $res = $this->httpClient->send(); $code = $res->getStatus(); if (intval($code / 100) !== 2) { throw new Net_WebFinger_Error('Error loading XRD file: ' . $res->getStatus() . ' ' . $res->getReasonPhrase(), Net_WebFinger_Error::NOT_FOUND); } $react->loadString($res->getBody()); } else { $context = stream_context_create(array('http' => array('user-agent' => 'PEAR Net_WebFinger', 'header' => 'accept: application/jrd+json, application/xrd+xml;q=0.9', 'follow_location' => true, 'max_redirects' => 20))); $content = @file_get_contents($url, false, $context); if ($content === false) { $msg = 'Error loading XRD file'; if (isset($http_response_header)) { $status = null; //we need this because there will be several HTTP/.. // status lines when redirection is going on. foreach ($http_response_header as $header) { if (substr($header, 0, 5) == 'HTTP/') { $status = $header; } } $msg .= ': ' . $status; } throw new Net_WebFinger_Error($msg, Net_WebFinger_Error::NOT_FOUND, new Net_WebFinger_Error('file_get_contents on ' . $url)); } $react->loadString($content); } } catch (Exception $e) { $react->error = $e; } return $react; }
function get_image() { $req = new HTTP_Request2(""); $image_url = $this->image_url; if (!$image_url) { return FALSE; } $req->setUrl($image_url); $response = $req->send(); if (strpos($response->getHeader("Content-Type"), 'image/jpeg') === 0 || strpos($response->getHeader("Content-Type"), 'image/gif') === 0 || strpos($response->getHeader("Content-Type"), 'image/bmp') === 0) { $fp = $response->getBody(); } else { return false; } $fp2 = fopen($this->image_path, "w"); if (!$fp || !$fp2) { echo "image error...<br />"; return false; } fputs($fp2, $fp); return TRUE; }
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 function testCookieJarAndRedirect() { $this->request->setUrl($this->baseUrl . 'redirects.php?special=cookie')->setConfig('follow_redirects', true)->setCookieJar(); $response = $this->request->send(); $this->assertEquals(serialize(array('cookie_on_redirect' => 'success')), $response->getBody()); }
/** * Store each crawl result to database * * @global array $_CONFIG * * @param \HTTP_Request2 $request http_request2() object * @param String $requestedUrl the requested url * @param String $refererUrl the lead url * @param Boolean $image the requested url is image or not * @param Integer $referPageId the lead url page id * @param String $requestedUrlText the requested url text * * @return null */ public function storeUrlInfos(\HTTP_Request2 $request, $requestedUrl, $refererUrl, $image, $referPageId, $requestedUrlText) { global $_CONFIG; try { $request->setUrl($requestedUrl); // ignore ssl issues // otherwise, contrexx does not activate 'https' when the server doesn't have an ssl certificate installed $request->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false, 'follow_redirects' => true)); $response = $request->send(); $urlStatus = $response->getStatus(); } catch (\Exception $e) { $response = true; $urlStatus = preg_match('#^[mailto:|javascript:]# i', $requestedUrl) ? 200 : 0; } if ($response) { $internalFlag = \Cx\Core_Modules\LinkManager\Controller\Url::isInternalUrl($requestedUrl); $flagStatus = $urlStatus == '200' ? 1 : 0; $linkType = $internalFlag ? 'internal' : 'external'; //find the entry name, module name, action and parameter if ($linkType == 'internal') { list($entryTitle, $moduleName, $moduleAction, $moduleParams) = $this->getModuleDetails($requestedUrl, $refererUrl, $image); } else { $objRefererUrl = $this->isModulePage($refererUrl); if ($objRefererUrl) { $entryTitle = $objRefererUrl->getTitle(); } $moduleName = ''; $moduleAction = ''; $moduleParams = ''; } if (!empty($referPageId)) { $backendReferUrl = ASCMS_PROTOCOL . '://' . $_CONFIG['domainUrl'] . ASCMS_PATH_OFFSET . '/cadmin/index.php?cmd=ContentManager&page=' . $referPageId; } //save the link $linkInputValues = array('lang' => contrexx_raw2db($this->langId), 'requestedPath' => contrexx_raw2db($requestedUrl), 'refererPath' => contrexx_raw2db($refererUrl), 'leadPath' => contrexx_raw2db($backendReferUrl), 'linkStatusCode' => contrexx_raw2db($urlStatus), 'entryTitle' => contrexx_raw2db($entryTitle), 'moduleName' => contrexx_raw2db($moduleName), 'moduleAction' => contrexx_raw2db($moduleAction), 'moduleParams' => contrexx_raw2db($moduleParams), 'detectedTime' => new \DateTime('now'), 'flagStatus' => contrexx_raw2db($flagStatus), 'linkStatus' => 0, 'linkRecheck' => 0, 'updatedBy' => 0, 'requestedLinkType' => contrexx_raw2db($linkType), 'brokenLinkText' => contrexx_raw2db($requestedUrlText)); $linkAlreadyExist = $this->linkRepo->findOneBy(array('requestedPath' => $requestedUrl)); if ($linkAlreadyExist && $linkAlreadyExist->getRefererPath() == $refererUrl) { if ($linkAlreadyExist->getLinkStatusCode() != $urlStatus) { //move the modified link to history table $historyInputValues = array('lang' => $linkAlreadyExist->getLang(), 'requestedPath' => $linkAlreadyExist->getRequestedPath(), 'refererPath' => $linkAlreadyExist->getRefererPath(), 'leadPath' => $linkAlreadyExist->getLeadPath(), 'linkStatusCode' => $linkAlreadyExist->getLinkStatusCode(), 'entryTitle' => $linkAlreadyExist->getEntryTitle(), 'moduleName' => $linkAlreadyExist->getModuleName(), 'moduleAction' => $linkAlreadyExist->getModuleAction(), 'moduleParams' => $linkAlreadyExist->getModuleParams(), 'detectedTime' => $linkAlreadyExist->getDetectedTime(), 'flagStatus' => $linkAlreadyExist->getFlagStatus(), 'linkStatus' => $linkAlreadyExist->getLinkStatus(), 'linkRecheck' => $linkAlreadyExist->getLinkRecheck(), 'updatedBy' => $linkAlreadyExist->getUpdatedBy(), 'requestedLinkType' => $linkAlreadyExist->getRequestedLinkType(), 'brokenLinkText' => $linkAlreadyExist->getBrokenLinkText()); $this->modifyHistory($historyInputValues); } //add the modified link to the link table $this->modifyLink($linkInputValues, $linkAlreadyExist); } else { //add the link to link table $this->modifyLink($linkInputValues); } } else { return; } }
/** * Sends request * * @param string $service * @param array $params * @return array json_decoded body **/ private function execute($service, $queryString) { $request = new HTTP_Request2(); try { $request->setMethod($this->httpMethod); $request->setHeader('Referer', $this->getHttpReferer()); $url = self::$apiUrl . $service . '?v=1.0'; if (isset($this->apiKey)) { $url .= '&key=' . $this->apiKey . '&'; } else { $url .= '&'; } $request->setUrl($url . substr($queryString, 0, -1)); $response = $request->send(); if ($response->getStatus() != 200) { throw new Services_Google_Translate_Exception('HTTP Error: ' . $response->getReasonPhrase()); } } catch (HTTP_Request2_Exception $e) { throw new Services_Google_Translate_Exception($e->getMessage()); } $decodedResponse = $this->decodeBody($request->send()->getBody()); return $decodedResponse; }
/** * Get the response for the given URL * * @staticvar \HTTP_Request2 $request Request instance * * @param string $url requested page url * * @return mixed \HTTP_Request2_Response | false */ public function getUrlResponse($url) { //If the argument url is empty then return if (empty($url)) { return false; } try { $request = new \HTTP_Request2(); $request->setUrl($url); // ignore ssl issues // otherwise, cloudrexx does not activate 'https' // when the server doesn't have an ssl certificate installed $request->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false, 'follow_redirects' => true)); return $request->send(); } catch (\Exception $e) { \DBG::log('An url ' . $url . ' is Failed to load, due to: ' . $e->getMessage()); } return false; }
/** * recheck all the links in the page and update those links status code * * @param array $recheckLinks rechecking links * @param array $inputArray default input values * @param \HTTP_Request2 $request http_request object */ public function recheckPage($recheckLinks, $inputArray, \HTTP_Request2 $request) { if (is_array($recheckLinks) && $request) { foreach ($recheckLinks as $link => $text) { $linkAlreadyExist = $this->linkRepository->getLinkByPath($link); if (!$linkAlreadyExist) { try { $request->setUrl($link); $request->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false, 'follow_redirects' => true)); $response = $request->send(); $urlStatus = $response->getStatus(); } catch (\Exception $e) { $urlStatus = preg_match('#^[mailto:|javascript:]# i', $link) ? 200 : 0; } $objFWUser = \FWUser::getFWUserObject(); $internalFlag = \Cx\Core_Modules\LinkManager\Controller\Url::isInternalUrl($link); $flagStatus = $urlStatus == '200' ? 1 : 0; $linkType = $internalFlag ? 'internal' : 'external'; $inputArray['requestedPath'] = contrexx_raw2db($link); $inputArray['linkStatusCode'] = contrexx_raw2db($urlStatus); $inputArray['flagStatus'] = contrexx_raw2db($flagStatus); $inputArray['linkRecheck'] = 1; $inputArray['requestedLinkType'] = contrexx_raw2db($linkType); $inputArray['linkStatus'] = 1; $inputArray['updatedBy'] = contrexx_raw2db($objFWUser->objUser->getId()); $inputArray['moduleName'] = ''; $inputArray['moduleAction'] = ''; $inputArray['moduleParams'] = ''; $inputArray['brokenLinkText'] = contrexx_raw2db($text); $this->modifyLink($inputArray); } } } }
set_include_path(".;C:\\php\\pear;D:\\home\\site\\wwwroot\\api\\HTTP"); require_once 'Request2.php'; //header("Content-Type: application/json; charset=utf-8"); header("Content-Type: text; charset=utf-8"); $json_string = file_get_contents('php://input'); $obj = json_decode($json_string, false); //get Params $url = $obj->url; $method = $obj->method; $header = (array) $obj->headers; $body = $obj->body; try { // リクエスト作成 $request = new HTTP_Request2(); $request->setHeader($header); $request->setUrl($url); if ($method == 'GET') { $request->setMethod(HTTP_Request2::METHOD_GET); } elseif ($method == 'POST') { $request->setMethod(HTTP_Request2::METHOD_POST); } elseif ($method == 'PUT') { $request->setMethod(HTTP_Request2::METHOD_PUT); } elseif ($method == 'DELETE') { $request->setMethod(HTTP_Request2::METHOD_DELETE); } else { die; } $request->setBody(trim($body)); $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false)); // レスポンス取得 $response = $request->send();
/** * Send data to CouchDB. This function dies on HTTP error and also if no * config.ini is found. * * @param array $data The object/document. * @param string $file The filename of the log currently being crunched. * @param int $count Which line are we at? * * @return void * @uses \HTTP_Request2 */ public static function sendToCouchDb(array $data, $file, $count) { static $config; if ($config === null) { $config = parse_ini_file(self::$base . '/config.ini', true); if ($config === false) { echo "Couldn't read config.ini."; exit(1); } } static $req; if ($req === null) { require_once 'HTTP/Request2.php'; $req = new \HTTP_Request2(); $req->setAuth($config['couchdb']['user'], $config['couchdb']['pass']); $req->setMethod(\HTTP_Request2::METHOD_PUT); } $obj = (object) $data; $id = md5($obj->line); // generate _id try { $req->setUrl($config['couchdb']['host'] . "/{$id}"); $req->setBody(json_encode($obj)); $resp = $req->send(); echo "\tDocument: {$id} (file: {$file}, line: {$count}), "; echo "Response: " . $resp->getStatus(); if ($resp->getStatus() == 409) { echo " [duplicate]"; } echo "\n"; unset($resp); unset($obj); unset($data); unset($id); } catch (Exception $e) { echo "Error: " . $e->getMessage(); exit(1); } }
public function testConvertUserinfoToAuth() { $req = new HTTP_Request2(); $req->setUrl('http://*****:*****@www.example.com/'); $this->assertEquals('', (string) $req->getUrl()->getUserinfo()); $this->assertEquals(array('user' => 'foo', 'password' => 'b@r', 'scheme' => HTTP_Request2::AUTH_BASIC), $req->getAuth()); }
/** * Compare given record with the already one in Solr * * @param array $record Record * @param string $logfile Log file where results are written * * @throws Exception * @return void */ protected function compareWithSolrRecord($record, $logfile) { global $configArray; $ignoreFields = ['allfields', 'allfields_unstemmed', 'fulltext', 'fulltext_unstemmed', 'spelling', 'spellingShingle', 'authorStr', 'author2Str', 'publisherStr', 'publishDateSort', 'topic_browse', 'hierarchy_browse', 'first_indexed', 'last_indexed', '_version_', 'fullrecord', 'title_full_unstemmed', 'title_fullStr', 'author_additionalStr']; if (isset($configArray['Solr']['ignore_in_comparison'])) { $ignoreFields = array_merge($ignoreFields, explode(',', $configArray['Solr']['ignore_in_comparison'])); } if (!isset($configArray['Solr']['search_url'])) { throw new Exception('search_url not set in ini file Solr section'); } $this->initSolrRequest(); $this->request->setMethod(HTTP_Request2::METHOD_GET); $url = $configArray['Solr']['search_url']; $url .= '?q=id:"' . urlencode($record['id']) . '"&wt=json'; $this->request->setUrl($url); $response = $this->request->send(); if ($response->getStatus() != 200) { $this->log->log('compareWithSolrRecord', "Could not fetch record (url {$url}), status code " . $response->getStatus()); return; } $solrResponse = json_decode($response->getBody(), true); $solrRecord = isset($solrResponse['response']['docs'][0]) ? $solrResponse['response']['docs'][0] : []; $differences = ''; $allFields = array_unique(array_merge(array_keys($record), array_keys($solrRecord))); $allFields = array_diff($allFields, $ignoreFields); foreach ($allFields as $field) { if (!isset($solrRecord[$field]) || !isset($record[$field]) || $record[$field] != $solrRecord[$field]) { $valueDiffs = ''; $values = isset($record[$field]) ? is_array($record[$field]) ? $record[$field] : [$record[$field]] : []; $solrValues = isset($solrRecord[$field]) ? is_array($solrRecord[$field]) ? $solrRecord[$field] : [$solrRecord[$field]] : []; foreach ($solrValues as $solrValue) { if (!in_array($solrValue, $values)) { $valueDiffs .= "--- {$solrValue}" . PHP_EOL; } } foreach ($values as $value) { if (!in_array($value, $solrValues)) { $valueDiffs .= "+++ {$value} " . PHP_EOL; } } if ($valueDiffs) { $differences .= "{$field}:" . PHP_EOL . $valueDiffs; } } } if ($differences) { $msg = "Record {$record['id']} would be changed: " . PHP_EOL . $differences . PHP_EOL; if ($logfile == '-') { echo $msg; } else { file_put_contents($logfile, $msg, FILE_APPEND); } } }
public function testAddCookieToJar() { $req = new HTTP_Request2(); $req->setCookieJar(); try { $req->addCookie('foo', 'bar'); $this->fail('Expected HTTP_Request2_Exception was not thrown'); } catch (HTTP_Request2_LogicException $e) { } $req->setUrl('http://example.com/path/file.php'); $req->addCookie('foo', 'bar'); $this->assertArrayNotHasKey('cookie', $req->getHeaders()); $cookies = $req->getCookieJar()->getAll(); $this->assertEquals(array('name' => 'foo', 'value' => 'bar', 'domain' => 'example.com', 'path' => '/path/', 'expires' => null, 'secure' => false), $cookies[0]); }
echo 'URL: ' . $serverAdder . PHP_EOL; echo 'Method: ' . $method . PHP_EOL; echo 'Language: ' . $language . PHP_EOL; echo 'UserAgent: ' . $userAgent . PHP_EOL; echo 'X-Image-Scale: ' . $imageScale . PHP_EOL; echo 'Gets: ' . PHP_EOL; print_r($gets); echo 'Posts: ' . PHP_EOL; print_r($posts); echo 'Cookies: ' . PHP_EOL; print_r($cookies); echo 'Uploads: ' . PHP_EOL; print_r($uploads); $HttpRequest = new HTTP_Request2(); $HttpRequest->setHeader(array('Accept-Language' => $language, 'User-Agent' => $userAgent, 'X-Image-Scale' => $imageScale)); $HttpRequest->setUrl($serverAdder); // 65秒待つ $HttpRequest->setConfig(array('timeout' => 65, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE)); eval('$HttpRequest->setMethod(HTTP_Request2::METHOD_' . $method . ');'); if (count($posts) > 0) { foreach ($posts as $keysKey => $keysVal) { $HttpRequest->addPostParameter($keysKey, $keysVal); } } if (count($cookies) > 0) { foreach ($cookies as $keysKey => $keysVal) { $HttpRequest->addCookie($keysKey, $keysVal); } } if (count($uploads) > 0) { for ($uploadCnt = 0; count($uploads) > $uploadCnt; $uploadCnt++) {
/** Save the photo to disk * @method savephoto * @param string path * @return boolean success */ function savephoto($path) { $req = new HTTP_Request2(""); $photo_url = $this->photo(); if (!$photo_url) { return FALSE; } $req->setUrl($photo_url); $response = $req->send(); if (strpos($response->getHeader("Content-Type"), 'image/jpeg') === 0 || strpos($response->getHeader("Content-Type"), 'image/gif') === 0 || strpos($response->getHeader("Content-Type"), 'image/bmp') === 0) { $fp = $response->getBody(); } else { //echo "<BR>*photoerror* ".$photo_url.": Content Type is '".$response->getHeader("Content-Type")."'<BR>".$response->getBody(); return false; } $fp2 = fopen($path, "w"); if (!$fp || !$fp2) { echo "image error...<BR>"; return false; } fputs($fp2, $fp); return TRUE; }
* specific language governing permissions and limitations * under the License. */ //PEAR package - needs to be installed: http://pear.php.net/package/HTTP_Request2/ require_once 'HTTP/Request2.php'; $openRegistryActivationAPI = new HTTP_Request2('https://dev-registry.rutgers.edu/api/v1/people/NETID/HR01/activation'); $openRegistryActivationAPI->setAuth('rats', 'RAT1234', HTTP_Request2::AUTH_BASIC); $openRegistryActivationAPI->setConfig(array('ssl_verify_peer' => false, 'ssl_verify_host' => false)); //Perform an HTTP POST request $openRegistryActivationAPI->setMethod(HTTP_Request2::METHOD_POST); $response = $openRegistryActivationAPI->send(); printf("Generate Activation Key call status: %d\n", $response->getStatus()); printf("New Activation Key resource Location: %s\n", $response->getHeader('Location')); printf("New Activation Key value: %s\n\n", array_pop(explode("/", $response->getHeader('Location')))); //Further process the activation key $openRegistryActivationAPI->setUrl($response->getHeader('Location')); verifyAndInvalidateActivationKey($openRegistryActivationAPI); function verifyAndInvalidateActivationKey($activationKeyResourceClient) { printf("Processing the activation key..............\n\n"); //Verify - HTTP GET $activationKeyResourceClient->setMethod(HTTP_Request2::METHOD_GET); $response = $activationKeyResourceClient->send(); switch ($response->getStatus()) { case 204: printf("The activation is valid!\n"); break; default: printf("%s\n", $response->getBody()); } //Now invalidate - HTTP DELETE
/** * 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; }
<?php require 'HTTP/Request2.php'; $r = new HTTP_Request2(); $r->setCookieJar(true); // log in $r->setUrl('https://bank.example.com/login.php?user=donald&password=b1gmoney$'); $page = $r->send()->getBody(); // retrieve account balance $r->setUrl('http://bank.example.com/balance.php?account=checking'); $page = $r->send()->getBody(); // make a deposit $r->setUrl('http://bank.example.com/deposit.php'); $r->setMethod(HTTP_Request2::METHOD_POST)->addPostParameter('account', 'checking')->addPostParameter('amount', '122.44'); $page = $r->send()->getBody();