本文整理汇总了PHP中HTTP_Request::setURL方法的典型用法代码示例。如果您正苦于以下问题:PHP HTTP_Request::setURL方法的具体用法?PHP HTTP_Request::setURL怎么用?PHP HTTP_Request::setURL使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HTTP_Request
的用法示例。
在下文中一共展示了HTTP_Request::setURL方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: SendTrackback
/**
* Send a trackback to a site
*
* @access public
* @param string $title Title of the Site
* @param string $excerpt The Excerpt
* @param string $permalink The Permalink to send
* @param array $to Where to send the trackback
*/
function SendTrackback($title, $excerpt, $permalink, $to)
{
$title = urlencode(stripslashes($title));
$excerpt = urlencode(stripslashes($excerpt));
$blog_name = urlencode(stripslashes($this->gadget->registry->fetch('site_name', 'Settings')));
$permalink = urlencode($permalink);
require_once PEAR_PATH . 'HTTP/Request.php';
$options = array();
$timeout = (int) $this->gadget->registry->fetch('connection_timeout', 'Settings');
$options['timeout'] = $timeout;
if ($this->gadget->registry->fetch('proxy_enabled', 'Settings') == 'true') {
if ($this->gadget->registry->fetch('proxy_auth', 'Settings') == 'true') {
$options['proxy_user'] = $this->gadget->registry->fetch('proxy_user', 'Settings');
$options['proxy_pass'] = $this->gadget->registry->fetch('proxy_pass', 'Settings');
}
$options['proxy_host'] = $this->gadget->registry->fetch('proxy_host', 'Settings');
$options['proxy_port'] = $this->gadget->registry->fetch('proxy_port', 'Settings');
}
$httpRequest = new HTTP_Request('', $options);
$httpRequest->setMethod(HTTP_REQUEST_METHOD_POST);
foreach ($to as $url) {
$httpRequest->setURL($url);
$httpRequest->addPostData('title', $title);
$httpRequest->addPostData('url', $permalink);
$httpRequest->addPostData('blog_name', $blog_name);
$httpRequest->addPostData('excerpt', $excerpt);
$resRequest = $httpRequest->sendRequest();
$httpRequest->clearPostData();
}
}
示例2: fetchData
function fetchData($username, $password)
{
switch ($this->options['cryptType']) {
case 'blowfish':
include_once 'Crypt/Blowfish.php';
$bf = new Crypt_Blowfish($this->options['cryptKey']);
$password = $bf->encrypt($password);
$password = base64_encode($password);
break;
default:
if (function_exists($this->options['cryptType'])) {
$password = $this->options['cryptType']($password);
}
break;
}
$req = new HTTP_Request();
$req->setURL($this->options['URL']);
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addQueryString($this->options['usernameKey'], $username);
$req->addQueryString($this->options['passwordKey'], $password);
if (!PEAR::isError($req->sendRequest())) {
$response = $req->getResponseBody();
} else {
return false;
}
$unserializer = new XML_Unserializer();
if ($unserializer->unserialize($response)) {
$this->result_value = $unserializer->getUnserializedData();
if ($this->result_value[$this->options['resultKey']] == $this->options['correctValue']) {
return true;
}
}
return false;
}
示例3: 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';
}
示例4: checkAddress
/**
* @param $values
*
* @return bool
*/
public static function checkAddress(&$values)
{
if (self::$_disabled) {
return FALSE;
}
if (!isset($values['street_address']) || !isset($values['city']) && !isset($values['state_province']) && !isset($values['postal_code'])) {
return FALSE;
}
$userID = Civi::settings()->get('address_standardization_userid');
$url = Civi::settings()->get('address_standardization_url');
if (empty($userID) || empty($url)) {
return FALSE;
}
$address2 = str_replace(',', '', $values['street_address']);
$XMLQuery = '<AddressValidateRequest USERID="' . $userID . '"><Address ID="0"><Address1>' . CRM_Utils_Array::value('supplemental_address_1', $values, '') . '</Address1><Address2>' . $address2 . '</Address2><City>' . $values['city'] . '</City><State>' . $values['state_province'] . '</State><Zip5>' . $values['postal_code'] . '</Zip5><Zip4>' . CRM_Utils_Array::value('postal_code_suffix', $values, '') . '</Zip4></Address></AddressValidateRequest>';
require_once 'HTTP/Request.php';
$request = new HTTP_Request();
$request->setURL($url);
$request->addQueryString('API', 'Verify');
$request->addQueryString('XML', $XMLQuery);
$response = $request->sendRequest();
$session = CRM_Core_Session::singleton();
$code = $request->getResponseCode();
if ($code != 200) {
$session->setStatus(ts('USPS Address Lookup Failed with HTTP status code: %1', array(1 => $code)));
return FALSE;
}
$responseBody = $request->getResponseBody();
$xml = simplexml_load_string($responseBody);
if (is_null($xml) || is_null($xml->Address)) {
$session->setStatus(ts('Your USPS API Lookup has Failed.'));
return FALSE;
}
if ($xml->Number == '80040b1a') {
$session->setStatus(ts('Your USPS API Authorization has Failed.'));
return FALSE;
}
if (array_key_exists('Error', $xml->Address)) {
$session->setStatus(ts('Address not found in USPS database.'));
return FALSE;
}
$values['street_address'] = (string) $xml->Address->Address2;
$values['city'] = (string) $xml->Address->City;
$values['state_province'] = (string) $xml->Address->State;
$values['postal_code'] = (string) $xml->Address->Zip5;
$values['postal_code_suffix'] = (string) $xml->Address->Zip4;
if (array_key_exists('Address1', $xml->Address)) {
$values['supplemental_address_1'] = (string) $xml->Address->Address1;
}
return TRUE;
}
示例5: getTerms
/**
* Extract terms from the Solr index.
*
* @param string $field Field to extract terms from
* @param string $start Starting term to extract (blank for beginning
* of list)
* @param int $limit Maximum number of terms to return (-1 for no
* limit)
* @param bool $returnSolrError Should we fail outright on syntax error
* (false) or treat it as an empty result set with an error key set (true)?
*
* @return array Associative array parsed from Solr JSON
* response; meat of the response is in the ['terms'] element, which contains
* an index named for the requested term, which in turn contains an associative
* array of term => count in index.
* @access public
*/
public function getTerms($field, $start, $limit, $returnSolrError = false)
{
$this->client->setMethod('GET');
$this->client->setURL($this->host . '/term');
$this->client->addQueryString('terms', 'true');
$this->client->addQueryString('terms.fl', $field);
$this->client->addQueryString('terms.lower.incl', 'false');
$this->client->addQueryString('terms.lower', $start);
$this->client->addQueryString('terms.limit', $limit);
$this->client->addQueryString('terms.sort', 'index');
$this->client->addQueryString('wt', 'json');
$result = $this->client->sendRequest();
if (!PEAR_Singleton::isError($result)) {
// Process the JSON response:
$data = $this->_process($this->client->getResponseBody(), $returnSolrError);
// Tidy the data into a more usable format:
if (isset($data['terms'])) {
$data['terms'] = array($data['terms'][0] => $this->_processTerms($data['terms'][1]));
}
return $data;
} else {
return $result;
}
}
示例6: Post
/**
* Post data to TypePad api server
*
* @access public
*/
function Post($method, $params, $apiKey = '')
{
$path = "/{$this->apiVersion}/{$method}";
if ($apiKey == '') {
$host = $this->apiServer;
} else {
$host = $apiKey . '.' . $this->apiServer;
}
$url = sprintf('http://%s:%s/%s/%s', $host, $this->apiPort, $this->apiVersion, $method);
require_once PEAR_PATH . 'HTTP/Request.php';
$options = array();
$timeout = (int) $GLOBALS['app']->Registry->fetch('connection_timeout', 'Settings');
$options['timeout'] = $timeout;
if ($GLOBALS['app']->Registry->fetch('proxy_enabled', 'Settings') == 'true') {
if ($GLOBALS['app']->Registry->fetch('proxy_auth', 'Settings') == 'true') {
$options['proxy_user'] = $GLOBALS['app']->Registry->fetch('proxy_user', 'Settings');
$options['proxy_pass'] = $GLOBALS['app']->Registry->fetch('proxy_pass', 'Settings');
}
$options['proxy_host'] = $GLOBALS['app']->Registry->fetch('proxy_host', 'Settings');
$options['proxy_port'] = $GLOBALS['app']->Registry->fetch('proxy_port', 'Settings');
}
$httpRequest = new HTTP_Request('', $options);
$httpRequest->setURL($url);
$httpRequest->addHeader('User-Agent', $this->userAgent);
$httpRequest->setMethod(HTTP_REQUEST_METHOD_POST);
foreach ($params as $key => $data) {
$httpRequest->addPostData($key, urlencode(stripslashes($data)));
}
$resRequest = $httpRequest->sendRequest();
if (PEAR::isError($resRequest)) {
return new Jaws_Error($resRequest->getMessage());
} elseif ($httpRequest->getResponseCode() != 200) {
return new Jaws_Error('HTTP response error ' . $httpRequest->getResponseCode(), 'Policy', JAWS_ERROR_ERROR);
}
return $httpRequest->getResponseBody();
}
示例7: trim
function u_web_caller($url = '')
{
//http
include_once 'HTTP/Request.php';
$url = trim($url);
//sanity
$url_pat = "@^(https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?)\$@ix";
//chk it
if (!@preg_match($url_pat, $url, $matches)) {
log_message('DEBUG', "u_web_caller() : Url INIT FAILED! [ {$url} ]");
return null;
}
//fwd
$req = new HTTP_Request();
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->setURL($url);
//get the response code
$req_code = !PEAR::isError($req->sendRequest()) ? $req->getResponseCode() : 800;
$body = $req_code == 200 ? trim($req->getResponseBody()) : '';
log_message('DEBUG', "u_web_caller() : get-url! [ {$req_code} / {$url} / {$body} ]");
//give it back ;-)
return array('status' => 200 == $req_code ? true : false, 'code' => $req_code, 'res' => $body);
}
示例8: renewItems
/**
* Try to renew a list of item barcodes
* - Return the new list of items on loan, with some errors
* built in to the data structure.
*
* @param array $patron The patron array from patronLogin
* @param array $item_list Array of barcodes to renew
*
* @return array Renewal status information
* @access public
*/
public function renewItems($patron, $item_list)
{
// Get items out on loan at the moment
$result = $this->getMyTransactions($patron);
// Make it more accessible - by barcode
$initial = array();
foreach ($result as $row) {
$initial[$row['barcode']] = $row;
}
// Get the iPortal server
$web_server = $this->_config['Catalog']['webhost'];
// Fake a login to get an authenticated session
$session_id = $this->_fakeLogin($patron);
$virtua_url = "http://{$web_server}/cgi-bin/chameleon";
$client = new HTTP_Request();
$client->setMethod(HTTP_REQUEST_METHOD_POST);
$client->setURL($virtua_url);
// Have to use addRawPostData() because of the way
// virtua expects the barcodes to come across.
// You can't mix addPostData() and addRawPostData()
// so they are all raw.
$post_data = "function=" . "RENEWAL";
$post_data .= "&search=" . "PATRON";
$post_data .= "&sessionid=" . "{$session_id}";
$post_data .= "&skin=" . "homepage";
$post_data .= "&lng=" . "en";
$post_data .= "&inst=" . "consortium";
$post_data .= "&conf=" . urlencode("./chameleon.conf");
$post_data .= "&u1=" . "12";
$post_data .= "&SourceScreen=" . "PATRONACTIVITY";
$post_data .= "&pos=" . "1";
$post_data .= "&patronid=" . $patron['cat_username'];
$post_data .= "&patronhost=" . urlencode($this->_config['Catalog']['patron_host']);
$post_data .= "&host=" . urlencode($this->_config['Catalog']['host_string']);
$post_data .= "&itembarcode=" . implode("&itembarcode=", $item_list);
$post_data .= "&submit=" . "Renew";
$post_data .= "&reset=" . "Clear";
$client->addRawPostData($post_data);
$result = $client->sendRequest();
// We don't care about errors, because we'll
// simply test for a change in the data.
// Get items out on loan with renewed info
$result = $this->getMyTransactions($patron);
// Foreach item currently on loan
$return = array();
foreach ($result as $row) {
// Did we even attempt to renew?
if (in_array($row['barcode'], $item_list)) {
// Yes, so check if the due date changed
if ($row['duedate'] != $initial[$row['barcode']]['duedate']) {
$row['error'] = false;
$row['renew_text'] = "Item successfully renewed.";
} else {
$row['error'] = true;
$row['renew_text'] = "Item renewal failed.";
}
$return[] = $row;
} else {
// No attempt to renew this item
$return[] = $row;
}
}
return $return;
}
示例9: getbXRecommendations
/**
* Get data and output in JSON
*
* @return void
* @access public
*/
public function getbXRecommendations()
{
global $configArray;
if (!isset($configArray['bX']['token'])) {
$this->output('bX support not enabled', JSON::STATUS_ERROR);
return;
}
$id = $_REQUEST['id'];
if (strncmp($id, 'metalib.', 8) == 0) {
include_once 'sys/MetaLib.php';
$metalib = new MetaLib();
if (!($record = $metalib->getRecord($id))) {
$this->output('Record does not exist', JSON::STATUS_ERROR);
return;
}
$openUrl = $record['openUrl'];
} elseif (strncmp($id, 'pci.', 4) == 0) {
include_once 'sys/PCI.php';
$pci = new PCI();
if (!($record = $pci->getRecord($id))) {
$this->output('Record does not exist', JSON::STATUS_ERROR);
return;
}
$openUrl = $record['openUrl'];
} else {
$searchObject = SearchObjectFactory::initSearchObject();
if (!($record = $searchObject->getIndexEngine()->getRecord($id))) {
$this->output('Record does not exist', JSON::STATUS_ERROR);
return;
}
$recordDriver = RecordDriverFactory::initRecordDriver($record);
$openUrl = $recordDriver->getOpenURL();
}
$params = http_build_query(array('token' => $configArray['bX']['token'], 'format' => 'xml', 'source' => isset($configArray['bX']['source']) ? $configArray['bX']['source'] : 'global', 'maxRecords' => isset($configArray['bX']['maxRecords']) ? $configArray['bX']['maxRecords'] : '5', 'threshold' => isset($configArray['bX']['threshold']) ? $configArray['bX']['threshold'] : '50'));
$openUrl .= '&res_dat=' . urlencode($params);
$baseUrl = isset($configArray['bX']['baseUrl']) ? $configArray['bX']['baseUrl'] : 'http://recommender.service.exlibrisgroup.com/service/recommender/openurl';
$client = new HTTP_Request();
$client->setMethod(HTTP_REQUEST_METHOD_GET);
$client->setURL($baseUrl . "?{$openUrl}");
$result = $client->sendRequest();
if (!PEAR::isError($result)) {
// Even if we get a response, make sure it's a 'good' one.
if ($client->getResponseCode() != 200) {
$this->output('bX request failed, response code ' . $client->getResponseCode(), JSON::STATUS_ERROR);
}
} else {
$this->_output('bX request failed: ' . $result, JSON::STATUS_ERROR);
}
$xml = simplexml_load_string($client->getResponseBody());
$data = array();
$jnl = 'info:ofi/fmt:xml:xsd:journal';
$xml->registerXPathNamespace('jnl', $jnl);
foreach ($xml->xpath('//jnl:journal') as $journal) {
$item = $this->convertToArray($journal, $jnl);
if (!isset($item['authors']['author'][0])) {
$item['authors']['author'] = array($item['authors']['author']);
}
$item['openurl'] = $this->createOpenUrl($item);
$data[] = $item;
}
$this->output($data, JSON::STATUS_OK);
}
示例10: export_datas_to_repo
function export_datas_to_repo()
{
$file = "/etc/artica-postfix/smtp.hacks.export.db";
if (!is_file($file)) {
echo "{$file} no such file\n";
return;
}
include_once "HTTP/Request.php";
$ini = new Bs_IniHandler();
$sock = new sockets();
$datas = $sock->GET_INFO("ArticaProxySettings");
$ini->loadString($datas);
$ArticaProxyServerEnabled = $ini->_params["PROXY"]["ArticaProxyServerEnabled"];
$ArticaProxyServerName = $ini->_params["PROXY"]["ArticaProxyServerName"];
$ArticaProxyServerPort = $ini->_params["PROXY"]["ArticaProxyServerPort"];
$ArticaProxyServerUsername = $ini->_params["PROXY"]["ArticaProxyServerUsername"];
$ArticaProxyServerUserPassword = $ini->_params["PROXY"]["ArticaProxyServerUserPassword"];
$req = new HTTP_Request("http://www.articatech.net/smtphack-import.php");
$req->setURL("http://www.articatech.net/smtphack-import.php");
$req->setMethod('POST');
if ($ArticaProxyServerEnabled == "yes") {
$req->setProxy($ArticaProxyServerName, $ArticaProxyServerPort, $ArticaProxyServerUsername, $ArticaProxyServerUserPassword);
}
$req->addPostData('xyz', time());
$result = $req->addFile('smtp-hack-file', $file, 'multipart/form-data');
// $req->sendRequest();
if (PEAR::isError($result)) {
echo $result->getMessage();
} else {
$response = $req->sendRequest();
if (PEAR::isError($response)) {
echo $response->getMessage();
return false;
}
if (preg_match("#SUCCESS#", $req->getResponseBody())) {
if ($GLOBALS["DEBUG"]) {
echo "Central server success\n" . $req->getResponseBody() . "\n";
}
return true;
}
if ($GLOBALS["DEBUG"]) {
echo "Central server failed\n" . $req->getResponseBody() . "\n";
}
}
}
示例11: lfDownloadZipFileFromJp
/**
* 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
*
* @return void
*/
function lfDownloadZipFileFromJp()
{
// Proxy経由を可能とする。
// TODO Proxyの設定は「data/module/HTTP/Request.php」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
$req = new HTTP_Request();
$req->setURL(ZIP_DOWNLOAD_URL);
// 郵便番号CSVをdownloadする。
$res = $req->sendRequest();
if (!$res || strlen($res) > 1) {
trigger_error(t('c_T_ARG1 retrieval failed._01', array('T_ARG1', ZIP_DOWNLOAD_URL)), E_USER_ERROR);
}
// 郵便番号CSV(zip file)を保存する。
$fp = fopen($this->zip_csv_temp_realfile, 'w');
if (!$fp) {
trigger_error(t('c_T_ARG1 cannot be opened._01', array('T_ARG1' => $this->zip_csv_temp_realfile)), E_USER_ERROR);
}
$res = fwrite($fp, $req->getResponseBody());
if (!$res) {
trigger_error(t('c_T_ARG1 writing failed._01', array('T_ARG1' => $this->zip_csv_temp_realfile)), E_USER_ERROR);
}
}
示例12: lfDownloadZipFileFromJp
/**
* 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
*
* @return void
*/
function lfDownloadZipFileFromJp()
{
// Proxy経由を可能とする。
// TODO Proxyの設定は「DATA_REALDIR . 'module/HTTP/Request.php'」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
$req = new HTTP_Request();
$req->setURL(ZIP_DOWNLOAD_URL);
// 郵便番号CSVをdownloadする。
$res = $req->sendRequest();
if (!$res) {
SC_Utils_Ex::sfDispException(ZIP_DOWNLOAD_URL . ' の取得に失敗しました。');
}
// 郵便番号CSV(zip file)を保存する。
$fp = fopen($this->zip_csv_temp_realfile, 'w');
if (!$fp) {
SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' を開けません。');
}
$res = fwrite($fp, $req->getResponseBody());
if (!$res) {
SC_Utils_Ex::sfDispException($this->zip_csv_temp_realfile . ' への書き込みに失敗しました。');
}
}
示例13: replace
function replace ($photo, $photo_id, $async = null) {
$upload_req = new HTTP_Request();
$upload_req->setMethod(HTTP_REQUEST_METHOD_POST);
$upload_req->setURL($this->Replace);
$upload_req->clearPostData();
//Process arguments, including method and login data.
$args = array("api_key" => $this->api_key, "photo_id" => $photo_id, "async" => $async);
if (!empty($this->email)) {
$args = array_merge($args, array("email" => $this->email));
}
if (!empty($this->password)) {
$args = array_merge($args, array("password" => $this->password));
}
if (!empty($this->token)) {
$args = array_merge($args, array("auth_token" => $this->token));
} elseif (!empty($_SESSION['phpFlickr_auth_token'])) {
$args = array_merge($args, array("auth_token" => $_SESSION['phpFlickr_auth_token']));
}
ksort($args);
$auth_sig = "";
foreach ($args as $key => $data) {
if ($data !== null) {
$auth_sig .= $key . $data;
$upload_req->addPostData($key, $data);
}
}
if (!empty($this->secret)) {
$api_sig = md5($this->secret . $auth_sig);
$upload_req->addPostData("api_sig", $api_sig);
}
$photo = realpath($photo);
$result = $upload_req->addFile("photo", $photo);
if (PEAR::isError($result)) {
die($result->getMessage());
}
//Send Requests
if ($upload_req->sendRequest()) {
$this->response = $upload_req->getResponseBody();
} else {
die("There has been a problem sending your command to the server.");
}
if ($async == 1)
$find = 'ticketid';
else
$find = 'photoid';
$rsp = explode("\n", $this->response);
foreach ($rsp as $line) {
if (ereg('<err code="([0-9]+)" msg="(.*)"', $line, $match)) {
if ($this->die_on_error)
die("The Flickr API returned the following error: #{$match[1]} - {$match[2]}");
else {
$this->error_code = $match[1];
$this->error_msg = $match[2];
$this->parsed_response = false;
return false;
}
} elseif (ereg("<" . $find . ">(.*)</", $line, $match)) {
$this->error_code = false;
$this->error_msg = false;
return $match[1];
}
}
}
示例14: 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());
}
示例15: lfDownloadZipFileFromJp
/**
* 日本郵便から郵便番号 CSV の ZIP アーカイブファイルを取得
*
* @return void
*/
function lfDownloadZipFileFromJp()
{
// Proxy経由を可能とする。
// TODO Proxyの設定は「data/module/HTTP/Request.php」内の「function HTTP_Request」へ記述する。いずれは、外部設定としたい。
$req = new HTTP_Request();
$req->setURL(ZIP_DOWNLOAD_URL);
// 郵便番号CSVをdownloadする。
$res = $req->sendRequest();
if (!$res || strlen($res) > 1) {
trigger_error(ZIP_DOWNLOAD_URL . ' の取得に失敗しました。', E_USER_ERROR);
}
// 郵便番号CSV(zip file)を保存する。
$fp = fopen($this->zip_csv_temp_realfile, 'w');
if (!$fp) {
trigger_error($this->zip_csv_temp_realfile . ' を開けません。', E_USER_ERROR);
}
$res = fwrite($fp, $req->getResponseBody());
if (!$res) {
trigger_error($this->zip_csv_temp_realfile . ' への書き込みに失敗しました。', E_USER_ERROR);
}
}