本文整理汇总了PHP中HTTP_Request::getResponseHeader方法的典型用法代码示例。如果您正苦于以下问题:PHP HTTP_Request::getResponseHeader方法的具体用法?PHP HTTP_Request::getResponseHeader怎么用?PHP HTTP_Request::getResponseHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HTTP_Request
的用法示例。
在下文中一共展示了HTTP_Request::getResponseHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: fetchUrlInfo
/** Récupèration d'informations à propos de la ressource désignée par $this->href.
*
* La récupération des infos se fait en cascade :
* 1. the encoding given in the charset parameter of the Content-Type HTTP header, or
* 2. the encoding given in the encoding attribute of the XML declaration within the document, or
* 3. utf-8.
*
* @see http://diveintomark.org/archives/2004/02/13/xml-media-types
* @todo Terminer la recherche d'infos
*/
function fetchUrlInfo()
{
// Envoi d'une requete vers l'URL
require_once 'HTTP/Request.php';
$r = new HTTP_Request($this->href);
$r->sendRequest();
// Récupération des informations contenues dans l'entête de la réponse.
$url_info = $r->getResponseHeader();
// --- Détermination du Content-Type et du Charset de la page --- //
// 1. D'apres un entete http
if (isset($url_info['content-type'])) {
// eg. text/html; charset=utf8
$pattern = '/^(\\w+\\/\\w+)(;?.\\w+=(.*))?/';
if (preg_match($pattern, $url_info['content-type'], $matches)) {
$content_type = isset($matches[1]) ? $matches[1] : null;
$charset = isset($matches[3]) ? $matches[3] : null;
}
} else {
$charset = 'utf8';
}
// Mise à jour des propriétés de l'objet en fonction des informations obtenues
$this->type = $content_type;
$this->charset = $charset;
return true;
}
示例2: prepare
/**
* preprocess Index action.
*
* @access public
* @return string Forward name (null if no errors.)
*/
function prepare()
{
if ($this->af->validate() == 0) {
/// download file
$url = sprintf('%s/repository.sphp', rtrim($this->af->get('repository_url'), '/'));
$cache_file = $this->backend->ctl->repositoryURL2CacheFile($url);
$repo_data = unserialize(file_get_contents($cache_file));
list($package, $version) = explode('@', $this->af->get('target_package'));
$urls = array();
foreach ($repo_data as $package_name => $package_data) {
if ($package_name == $package) {
foreach ($package_data as $_pdata) {
if ($_pdata['version'] == $version) {
$urls = $_pdata['urls'];
$filesize = $_pdata['size'];
}
}
}
}
require_once 'HTTP/Request.php';
$req = new HTTP_Request();
$req->setMethod(HTTP_REQUEST_METHOD_HEAD);
$command = 'no command';
foreach ($urls as $_url_data) {
$_url = $_url_data['url'];
$req->setURL($_url);
$req->sendRequest();
if ($req->getResponseCode() == "302") {
$headers = $req->getResponseHeader();
$req->setURL($headers['location']);
}
$req->sendRequest();
if ($req->getResponseCode() == '200') {
$data_file = $this->backend->ctl->package2dataFile($package, $version);
if ($this->fetchTgzFile($data_file, $req->getUrl())) {
if (filesize($data_file) == $filesize || !$filesize) {
chmod($data_file, 0666);
return null;
}
}
}
}
$this->ae->add('wget failed', _('file download failed.') . '[debug]' . sprintf('SIZE:[datafile,%d => repos,%d]', filesize($data_file), $filesize));
}
return 'json_error_reload';
}
示例3: iconv
/**
* @brief rss 주소로 부터 내용을 받아오는 함수
*
* tistory 의 경우 원본 주소가 location 헤더를 뿜는다.(내용은 없음) 이를 해결하기 위한 수정
**/
function rss_request($rss_url)
{
// request rss
$rss_url = Context::convertEncodingStr($rss_url);
$URL_parsed = parse_url($rss_url);
if (strpos($URL_parsed["host"], 'naver.com')) {
$rss_url = iconv('UTF-8', 'euc-kr', $rss_url);
}
$rss_url = str_replace(array('%2F', '%3F', '%3A', '%3D', '%3B', '%26'), array('/', '?', ':', '=', ';', '&'), urlencode($rss_url));
$URL_parsed = parse_url($rss_url);
$host = $URL_parsed["host"];
$port = $URL_parsed["port"];
if ($port == 0) {
$port = 80;
}
$path = $URL_parsed["path"];
if ($URL_parsed["query"] != '') {
$path .= "?" . $URL_parsed["query"];
}
$oReqeust = new HTTP_Request($rss_url);
$oReqeust->addHeader('Content-Type', 'application/xml');
$oReqeust->addHeader('User-agent', 'RSS Reader Widget (XE ' . __ZBXE_VERSION__ . ' (http://www.xpressengine.com); PEAR HTTP_Request class (http://pear.php.net))');
$oReqeust->setMethod('GET');
$user = $URL_parsed["user"];
$pass = $URL_parsed["pass"];
if ($user) {
$oReqeust->setBasicAuth($user, $pass);
}
$oResponse = $oReqeust->sendRequest();
if (PEAR::isError($oResponse)) {
return;
}
$header = $oReqeust->getResponseHeader();
if ($header['location']) {
return $this->rss_request(trim($header['location']));
} else {
return $oReqeust->getResponseBody();
}
}
示例4: PNB_getPingbackUrl
/**
* Get the Pingback URL for a given URL
*
* @param string $url URL to get the Pingback URL for
* @return string Pingback URL or empty string
*
*/
function PNB_getPingbackUrl($url)
{
require_once 'HTTP/Request.php';
$retval = '';
$req = new HTTP_Request($url);
$req->setMethod(HTTP_REQUEST_METHOD_HEAD);
$req->addHeader('User-Agent', 'glFusion/' . GVERSION);
$response = $req->sendRequest();
if (PEAR::isError($response)) {
COM_errorLog('Pingback (HEAD): ' . $response->getMessage());
return false;
} else {
$retval = $req->getResponseHeader('X-Pingback');
}
if (empty($retval)) {
// search for <link rel="pingback">
$req = new HTTP_Request($url);
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader('User-Agent', 'glFusion/' . GVERSION);
$response = $req->sendRequest();
if (PEAR::isError($response)) {
COM_errorLog('Pingback (GET): ' . $response->getMessage());
return false;
} elseif ($req->getResponseCode() == 200) {
$body = $req->getResponseBody();
// only search for the first match - it doesn't make sense to have
// more than one pingback URL
$found = preg_match("/<link rel=\"pingback\"[^>]*href=[\"']([^\"']*)[\"'][^>]*>/i", $body, $matches);
if ($found === 1 && !empty($matches[1])) {
$url = str_replace('&', '&', $matches[1]);
$retval = urldecode($url);
}
} else {
COM_errorLog('Pingback (GET): Got HTTP response code ' . $req->getResponseCode() . " when requesting {$url}");
return false;
}
}
return $retval;
}
示例5: get
/**
* Retrieve Free/Busy data for the specified resource.
*
* @param string $resource Fetch the Free/Busy data for this resource.
*
* @return Horde_Icalendar_Vfreebusy The Free/Busy data.
*/
public function get($resource)
{
global $conf;
$url = self::getUrl($resource);
Horde::log(sprintf('Freebusy URL for resource %s is %s', $resource, $url), 'DEBUG');
list($user, $domain) = explode('@', $resource);
if (empty($domain)) {
$domain = $conf['kolab']['filter']['email_domain'];
}
/**
* This section matches Kronolith_Freebusy and should be merged with it
* again in a single Horde_Freebusy module.
*/
$options = array('method' => 'GET', 'timeout' => 5, 'allowRedirects' => true);
if (!empty($conf['http']['proxy']['proxy_host'])) {
$options = array_merge($options, $conf['http']['proxy']);
}
$http = new HTTP_Request($url, $options);
$http->setBasicAuth($conf['kolab']['filter']['calendar_id'] . '@' . $domain, $conf['kolab']['filter']['calendar_pass']);
@$http->sendRequest();
if ($http->getResponseCode() != 200) {
throw new Horde_Kolab_Resource_Exception(sprintf('Unable to retrieve free/busy information for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY);
}
$vfb_text = $http->getResponseBody();
// Detect the charset of the iCalendar data.
$contentType = $http->getResponseHeader('Content-Type');
if ($contentType && strpos($contentType, ';') !== false) {
list(, $charset, ) = explode(';', $contentType);
$vfb_text = Horde_String::convertCharset($vfb_text, trim(str_replace('charset=', '', $charset)), 'UTF-8');
}
$iCal = new Horde_Icalendar();
$iCal->parsevCalendar($vfb_text, 'VCALENDAR');
$vfb =& $iCal->findComponent('VFREEBUSY');
if ($vfb === false) {
throw new Horde_Kolab_Resource_Exception(sprintf('Invalid or no free/busy information available for %s', $resource), Horde_Kolab_Resource_Exception::NO_FREEBUSY);
}
$vfb->simplify();
return $vfb;
}
示例6: getResponseHeaders
function getResponseHeaders()
{
return $this->HttpRequest->getResponseHeader();
}
示例7: array
function _request($url, $body = null, $content_type = 'text/html', $method = 'GET', $headers = array(), $cookies = array())
{
set_include_path(_XE_PATH_ . "libs/PEAR");
require_once 'PEAR.php';
require_once 'HTTP/Request.php';
$url_info = parse_url($url);
$host = $url_info['host'];
if (__PROXY_SERVER__ !== null) {
$oRequest = new HTTP_Request(__PROXY_SERVER__);
$oRequest->setMethod('POST');
$oRequest->addPostData('arg', serialize(array('Destination' => $url, 'method' => $method, 'body' => $body, 'content_type' => $content_type, "headers" => $headers)));
} else {
$oRequest = new HTTP_Request($url);
if (count($headers)) {
foreach ($headers as $key => $val) {
$oRequest->addHeader($key, $val);
}
}
if ($cookies[$host]) {
foreach ($cookies[$host] as $key => $val) {
$oRequest->addCookie($key, $val);
}
}
if (!$content_type) {
$oRequest->addHeader('Content-Type', 'text/html');
} else {
$oRequest->addHeader('Content-Type', $content_type);
}
$oRequest->setMethod($method);
if ($body) {
$oRequest->setBody($body);
}
}
$oResponse = $oRequest->sendRequest();
$code = $oRequest->getResponseCode();
$header = $oRequest->getResponseHeader();
$response = $oRequest->getResponseBody();
if ($c = $oRequest->getResponseCookies()) {
foreach ($c as $k => $v) {
$cookies[$host][$v['name']] = $v['value'];
}
}
if ($code > 300 && $code < 399 && $header['location']) {
return $this->_request($header['location'], $body, $content_type, $method, $headers, $cookies);
}
if ($code != 200) {
return;
}
return $response;
}
示例8: fetchUrlPear
function fetchUrlPear($url, $request_parameters)
{
if (VERBOSE) {
logEvent($url . ' fetching with PEAR');
}
if (0 && $GLOBALS['has_pear_http_request'] == 2) {
$headreq = new HTTP_Request2($url, $request_parameters);
$headreq->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)');
} else {
$headreq = new HTTP_Request($url, $request_parameters);
$headreq->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)');
}
if (!PEAR::isError($headreq->sendRequest(false))) {
$code = $headreq->getResponseCode();
if ($code != 200) {
logEvent('Fetching ' . $url . ' failed, error code ' . $code);
return 0;
}
$header = $headreq->getResponseHeader();
if (preg_match('/charset=(.*)/i', $header['content-type'], $regs)) {
$remote_charset = strtoupper($regs[1]);
}
$request_parameters['method'] = 'GET';
if (0 && $GLOBALS['has_pear_http_request'] == 2) {
$req = new HTTP_Request2($url, $request_parameters);
$req->setHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)');
} else {
$req = new HTTP_Request($url, $request_parameters);
$req->addHeader('User-Agent', 'phplist v' . VERSION . 'p (http://www.phplist.com)');
}
logEvent('Fetching ' . $url);
if (VERBOSE && function_exists('output')) {
output('Fetching remote: ' . $url);
}
if (!PEAR::isError($req->sendRequest(true))) {
$content = $req->getResponseBody();
if ($remote_charset != 'UTF-8' && function_exists('iconv')) {
$content = iconv($remote_charset, 'UTF-8//TRANSLIT', $content);
}
} else {
logEvent('Fetching ' . $url . ' failed on GET ' . $req->getResponseCode());
return 0;
}
} else {
logEvent('Fetching ' . $url . ' failed on HEAD');
return 0;
}
return $content;
}
示例9: extractPage
public function extractPage($url, $match, $replace, $referer, $source, $ident = null)
{
global $_conf;
$ret = array();
$source = @preg_replace('{' . $match . '}', $source, $url);
$get_url = $referer;
if ($this->extractErrors[$get_url]) {
// 今回リクエストでエラーだった場合
return $this->cacheData[$url] && $this->cacheData[$url]['data'] ? $this->cacheData[$url]['data'] : $ret;
}
$params = array();
$params['timeout'] = $_conf['http_conn_timeout'];
$params['readTimeout'] = array($_conf['http_read_timeout'], 0);
if ($_conf['proxy_use']) {
$params['proxy_host'] = $_conf['proxy_host'];
$params['proxy_port'] = $_conf['proxy_port'];
}
$req = new HTTP_Request($get_url, $params);
if ($this->cacheData[$url] && $this->cacheData[$url]['responseHeaders'] && $this->cacheData[$url]['responseHeaders']['last-modified'] && strlen($this->cacheData[$url]['responseHeaders']['last-modified'])) {
$req->addHeader("If-Modified-Since", $this->cacheData[$url]['responseHeaders']['last-modified']);
}
$req->addHeader('User-Agent', !empty($_conf['expack.user_agent']) ? $_conf['expack.user_agent'] : $_SERVER['HTTP_USER_AGENT']);
$response = $req->sendRequest();
$code = $req->getResponseCode();
if (PEAR::isError($response) || $code != 200 && $code != 206 && $code != 304) {
$errmsg = PEAR::isError($response) ? $response->getMessage() : $code;
// 今回リクエストでのエラーをオンラインキャッシュ
$this->extractErrors[$get_url] = $errmsg;
// サーバエラー以外なら永続キャッシュに保存
if ($code && $code < 500) {
// ページが消えている場合
if ($this->_checkLost($url, $ret)) {
return $this->cacheData[$url]['data'];
}
$this->storeCache($url, array('code' => $code, 'errmsg' => $errmsg, 'responseHeaders' => $req->getResponseHeader(), 'data' => $ret));
}
return $this->cacheData[$url] && $this->cacheData[$url]['data'] ? $this->cacheData[$url]['data'] : $ret;
}
if ($code == 304 && $this->cacheData[$url]) {
return $this->cacheData[$url]['data'];
}
$body = $req->getResponseBody();
preg_match_all('{' . $source . '}i', $body, $extracted, PREG_SET_ORDER);
foreach ($extracted as $i => $extract) {
$_url = $replace;
$_referer = $referer;
foreach ($extract as $j => $part) {
if ($j < 1) {
continue;
}
$_url = str_replace('$EXTRACT' . $j, $part, $_url);
$_referer = str_replace('$EXTRACT' . $j, $part, $_referer);
}
if ($extract[1]) {
$_url = str_replace('$EXTRACT', $part, $_url);
$_referer = str_replace('$EXTRACT', $part, $_referer);
}
$ret[$i]['url'] = $_url;
$ret[$i]['referer'] = $_referer;
}
// ページが消えている場合
if ($this->_checkLost($url, $ret)) {
return $this->cacheData[$url]['data'];
}
if ($ident && $this->cacheData[$url] && $this->cacheData[$url]['data']) {
$ret = self::_identByCacheData($ret, $this->cacheData[$url]['data'], $ident);
}
// 結果を永続キャッシュに保存
$this->storeCache($url, array('code' => $code, 'responseHeaders' => $req->getResponseHeader(), 'data' => $ret));
return $ret;
}
示例10: phpversion
function mod_time($uri)
{
if (function_exists('version_compare') && version_compare(phpversion(), '4.3.0') >= 0) {
require_once S9Y_PEAR_PATH . 'HTTP/Request.php';
serendipity_request_start();
$req = new HTTP_Request($uri);
if (PEAR::isError($req->sendRequest()) || $req->getResponseCode() != '200') {
serendipity_request_end();
return false;
}
$fHeader = $req->getResponseHeader();
if (isset($fHeader['last-modified'])) {
$modtime = $fHeader['last-modified'];
}
serendipity_request_end();
} else {
$parts = parse_url($uri);
$host = $parts['host'];
$path = $parts['path'];
if (!($fp = @fsockopen($host, 80))) {
return false;
}
$req = "HEAD {$path} HTTP/1.1\r\nUser-Agent: PHP/" . phpversion();
$req .= "\r\nHost: {$host}\r\nAccept: */*\r\n\r\n";
fputs($fp, $req);
while (!feof($fp)) {
$str = fgets($fp, 4096);
if (strpos(strtolower($str), 'last-modified') !== false) {
$modtime = substr($str, 15);
break;
}
}
fclose($fp);
}
return isset($modtime) ? $modtime : 0;
}
示例11: PNB_handlePingback
/**
* Handle a pingback for an entry.
*
* Also takes care of the speedlimit and spam. Assumes that the caller of this
* function has already checked permissions!
*
* @param string $id ID of entry that got pinged
* @param string $type type of that entry ('article' for stories, etc.)
* @param string $url URL of the page that pinged us
* @param string $oururl URL that got pinged on our site
* @return object XML-RPC response
*
*/
function PNB_handlePingback($id, $type, $url, $oururl)
{
global $_CONF, $_TABLES, $PNB_ERROR;
require_once 'HTTP/Request.php';
if (!isset($_CONF['check_trackback_link'])) {
$_CONF['check_trackback_link'] = 2;
}
// handle pingbacks to articles on our own site
$skip_speedlimit = false;
if ($_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR']) {
if (!isset($_CONF['pingback_self'])) {
$_CONF['pingback_self'] = 0;
// default: skip self-pingbacks
}
if ($_CONF['pingback_self'] == 0) {
return new XML_RPC_Response(new XML_RPC_Value($PNB_ERROR['skipped']));
} else {
if ($_CONF['pingback_self'] == 2) {
$skip_speedlimit = true;
}
}
}
COM_clearSpeedlimit($_CONF['commentspeedlimit'], 'pingback');
if (!$skip_speedlimit) {
$last = COM_checkSpeedlimit('pingback');
if ($last > 0) {
return new XML_RPC_Response(0, 49, sprintf($PNB_ERROR['speedlimit'], $last, $_CONF['commentspeedlimit']));
}
}
// update speed limit in any case
COM_updateSpeedlimit('pingback');
if ($_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']) {
if ($_CONF['check_trackback_link'] & 4) {
$parts = parse_url($url);
if (empty($parts['host'])) {
TRB_logRejected('Pingback: No valid URL', $url);
return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
} else {
$ip = gethostbyname($parts['host']);
if ($ip != $_SERVER['REMOTE_ADDR']) {
TRB_logRejected('Pingback: IP address mismatch', $url);
return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']);
}
}
}
}
// See if we can read the page linking to us and extract at least
// the page's title out of it ...
$title = '';
$excerpt = '';
$req = new HTTP_Request($url);
$req->addHeader('User-Agent', 'Geeklog/' . VERSION);
$response = $req->sendRequest();
if (PEAR::isError($response)) {
if ($_CONF['check_trackback_link'] & 3) {
// we were supposed to check for backlinks but didn't get the page
COM_errorLog("Pingback verification: " . $response->getMessage() . " when requesting {$url}");
return new XML_RPC_Response(0, 33, $PNB_ERROR['uri_invalid']);
}
// else: silently ignore errors - we'll simply do without the title
} else {
if ($req->getResponseCode() == 200) {
$body = $req->getResponseBody();
if ($_CONF['check_trackback_link'] & 3) {
if (!TRB_containsBacklink($body, $oururl)) {
TRB_logRejected('Pingback: No link to us', $url);
$comment = TRB_formatComment($url);
PLG_spamAction($comment, $_CONF['spamx']);
return new XML_RPC_Response(0, 49, $PNB_ERROR['spam']);
}
}
preg_match(':<title>(.*)</title>:i', $body, $content);
if (empty($content[1])) {
$title = '';
// no title found
} else {
$title = trim(COM_undoSpecialChars($content[1]));
}
if ($_CONF['pingback_excerpt']) {
// Check which character set the site that sent the Pingback
// is using
$charset = 'ISO-8859-1';
// default, see RFC 2616, 3.7.1
$ctype = $req->getResponseHeader('Content-Type');
if (!empty($ctype)) {
// e.g. text/html; charset=utf-8
$c = explode(';', $ctype);
//.........这里部分代码省略.........
示例12: fetchUrl
function fetchUrl($url, $userdata = array())
{
require_once "HTTP/Request.php";
# logEvent("Fetching $url");
if (sizeof($userdata)) {
foreach ($userdata as $key => $val) {
$url = eregi_replace("\\[{$key}\\]", urlencode($val), $url);
}
}
if (!isset($GLOBALS['urlcache'])) {
$GLOBALS['urlcache'] = array();
}
# keep in memory cache in case we send a page to many emails
if (isset($GLOBALS['urlcache'][$url]) && is_array($GLOBALS['urlcache'][$url]) && time() - $GLOBALS['urlcache'][$url]['fetched'] < REMOTE_URL_REFETCH_TIMEOUT) {
# logEvent($url . " is cached in memory");
return $GLOBALS['urlcache'][$url]['content'];
}
$dbcache_lastmodified = getPageCacheLastModified($url);
$timeout = time() - $dbcache_lastmodified;
if (time() - $dbcache_lastmodified < REMOTE_URL_REFETCH_TIMEOUT) {
# logEvent($url.' is cached in database');
return getPageCache($url);
} else {
# logEvent($url.' is not cached in database '.$timeout.' '. $dbcache_lastmodified." ".time());
}
# add a small timeout, although the biggest timeout will exist in doing the DNS lookup,
# so it won't make too much of a difference
$request_parameters = array('timeout' => 10, 'allowRedirects' => 1, 'method' => 'HEAD');
$headreq = new HTTP_Request($url, $request_parameters);
$headreq->addHeader('User-Agent', 'phplist v' . VERSION . ' (http://www.phplist.com)');
if (!PEAR::isError($headreq->sendRequest(false))) {
$code = $headreq->getResponseCode();
if ($code != 200) {
logEvent('Fetching ' . $url . ' failed, error code ' . $code);
return 0;
}
$header = $headreq->getResponseHeader();
$lastmodified = strtotime($header["last-modified"]);
$cache = getPageCache($url, $lastmodified);
if (!$cache) {
$request_parameters['method'] = 'GET';
$req = new HTTP_Request($url, $request_parameters);
$req->addHeader('User-Agent', 'phplist v' . VERSION . ' (http://www.phplist.com)');
logEvent('Fetching ' . $url);
if (!PEAR::isError($req->sendRequest(true))) {
$content = $req->getResponseBody();
$content = addAbsoluteResources($content, $url);
logEvent('Fetching ' . $url . ' success');
setPageCache($url, $lastmodified, $content);
} else {
logEvent('Fetching ' . $url . ' failed');
return 0;
}
} else {
logEvent($url . ' was cached in database');
$content = $cache;
}
} else {
logEvent('Fetching ' . $url . ' failed');
return 0;
}
$GLOBALS['urlcache'][$url] = array('fetched' => time(), 'content' => $content);
return $content;
}
示例13: getHttpResponse
/**
* Return array contains the response of the given URL.
* array[code] => HTTP status code
* array[headers] => HTTP headers
* array[headers] => Entity body
* Throw exception if error.
*
* @param string $url
* @param array $headers
* @param array $post
* @return array
*/
private function getHttpResponse($url, $headers = array(), $post = array())
{
$url = str_replace('&', '&', trim($url));
$req = new HTTP_Request($url, array('allowRedirects' => true, 'maxRedirects' => 5));
/*
* @see HTTP_Request_Listener_Extended
*/
$listener = new HTTP_Request_Listener_Extended();
$req->attach($listener);
if (!isset($headers['user-agent'])) {
$headers['user-agent'] = $this->httpUserAgent;
}
foreach ($headers as $key => $value) {
if (!empty($value)) {
$req->addHeader($key, $value);
}
}
if (!empty($post)) {
$req->setMethod('POST');
foreach ($post as $key => $value) {
$req->addPostData($key, $value);
}
}
$result = $req->sendRequest();
$is_error = false;
if (PEAR::isError($result)) {
$is_error = true;
$error_message = $result->getMessage();
/*
* $error_message could be empty if the error was raised
* when fsockopen() returns false in Net_Socket::connect()
*/
if (empty($error_message)) {
$error_message = "Failed connecting to the server.";
/*
* HTTP_Request raises 'Malformed response' error
* if request path is empty (e.g. http://www.example.com).
* This bug still exists in its automatic redirection mechanism
* in CVS rev. 1.55 (latest as of May 18, 2007).
*/
} elseif ($error_message == 'Malformed response.') {
$url = $req->getURL(null);
if (false !== ($urls = @parse_url($url)) and !isset($urls['path'])) {
$req->setURL($url);
$result = $req->sendRequest();
if (PEAR::isError($result)) {
$error_message = $result->getMessage();
if (empty($error_message)) {
$error_message = "Failed connecting to the server.";
}
} else {
$is_error = false;
}
}
}
}
if ($is_error) {
throw new Exception($error_message);
}
return array('url' => $req->getUrl(null), 'code' => $req->getResponseCode(), 'headers' => $req->getResponseHeader(), 'body' => $req->getResponseBody());
}
示例14: shuttle_url
//.........这里部分代码省略.........
// open a stream and send the request
$fp = fopen($url, 'r', false, $context);
if (!$fp) {
$err = PEAR::raiseError(sprintf('Cannot connect to %s.', $url));
self::push_error($err);
return $err;
}
if ($outsec >= 0) {
stream_set_timeout($fp, $outsec);
}
// process the response
$meta_data = stream_get_meta_data($fp);
if (strcasecmp($meta_data['wrapper_type'], 'cURL') == 0) {
$errmsg = 'EstraierPure does not work with the cURL'
. ' HTTP stream wrappers, please use PEAR::HTTP_Request.';
$err = PEAR::raiseError($errmsg);
self::push_error($err);
return $err;
}
if (!empty($meta_data['timed_out'])) {
$err = PEAR::raiseError('Connection timed out.');
self::push_error($err);
return $err;
}
$first_header = array_shift($meta_data['wrapper_data']);
if (!preg_match('!^HTTP/(.+?) (\\d+) ?(.*)!', $first_header, $matches)) {
$err = PEAR::raiseError('Malformed response.');
self::push_error($err);
return $err;
}
$code = intval($matches[2]);
if ($res instanceof EstraierPure_Response) {
if ($res->save_heads) {
foreach ($meta_data['wrapper_data'] as $header) {
list($name, $value) = explode(':', $header, 2);
$res->add_head(strtolower($name), ltrim($value));
}
}
if ($res->save_body) {
$res->set_body(stream_get_contents($fp));
}
}
// close the stream
fclose($fp);
// }}}
} else {
// {{{{ using PEAR::HTTP_Request
// set request parameters
$params = array();
$params['requestHeaders'] = $reqheads;
if (isset($params['requestHeaders']['Content-Type'])) {
unset($params['requestHeaders']['Content-Type']);
$params['requestHeaders']['content-type'] = $reqheads['Content-Type'];
}
if (!is_null($pxhost)) {
$params['proxy_host'] = $pxhost;
$params['proxy_port'] = $pxport;
}
if ($outsec >= 0) {
$params['timeout'] = floatval($outsec);
$params['readTimeout'] = array($outsec, 0);
}
// create an instance of HTTP_Request
$req = new HTTP_Request($url, $params);
if (is_null($reqbody)) {
$req->setMethod('GET');
} else {
$req->setMethod('POST');
$req->setBody($reqbody);
}
// send the request
$err = $req->sendRequest(is_object($res) && !empty($res->save_body));
if (PEAR::isError($err)) {
self::push_error($err);
return $err;
}
$code = $req->getResponseCode();
// process the response
if ($res instanceof EstraierPure_Response) {
if ($res->save_heads) {
$res->set_heads($req->getResponseHeader());
}
if ($res->save_body) {
$res->set_body($req->getResponseBody());
}
}
// }}}
}
return $code;
}
示例15: callMethod
function callMethod($method, $params = array())
{
$this->_err_code = 0;
$this->_err_msg = '';
#
# create the POST body
#
$p = $params;
$p['method'] = $method;
$p['api_key'] = $this->_cfg['api_key'];
if ($this->_cfg['api_secret']) {
$p['api_sig'] = $this->signArgs($p);
}
$p2 = array();
foreach ($p as $k => $v) {
$p2[] = urlencode($k) . '=' . urlencode($v);
}
$body = implode('&', $p2);
#
# create the http request
#
$req = new HTTP_Request($this->_cfg['endpoint'], array('timeout' => $this->_cfg['conn_timeout']));
$req->_readTimeout = array($this->_cfg['io_timeout'], 0);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addRawPostData($body);
$req->sendRequest();
$this->_http_code = $req->getResponseCode();
$this->_http_head = $req->getResponseHeader();
$this->_http_body = $req->getResponseBody();
if ($this->_http_code != 200) {
$this->_err_code = 0;
if ($this->_http_code) {
$this->_err_msg = "Bad response from remote server: HTTP status code {$this->_http_code}";
} else {
$this->_err_msg = "Couldn't connect to remote server";
}
return 0;
}
#
# create xml tree
#
$dom = new DOMDocument();
$dom->loadXML($this->_http_body);
$xp = new DOMXPath($dom);
#
# check we got an <rsp> element at the root
#
if (!$xp->query("/rsp")->length) {
$this->_err_code = 0;
$this->_err_msg = "Bad XML response";
return 0;
}
#
# stat="fail" ?
#
$stat = $xp->query("/rsp/@stat")->item(0)->value;
if ($stat == 'fail') {
$n = null;
foreach ($xp->query("/rsp/err") as $err) {
$this->_err_code = $xp->query("@code", $err)->item(0)->value;
$this->_err_msg = $xp->query("@msg", $err)->item(0)->value;
}
return 0;
}
#
# weird status
#
if ($stat != 'ok') {
$this->_err_code = 0;
$this->_err_msg = "Unrecognised REST response status";
return 0;
}
#
# return the tree
#
return array($dom, $xp, $this->_http_body);
}