星期一, 十一月 27, 2006

Code:简单的服务器端发送http请求

Tag:php,rpc,socket,post

因为手里需要所以简单的写了点点,但没有对后期数据进行处理,也没有加异常处理
先用之,再改进...

$remove_url="http://localhost/worktest/test_server.php";
// Create the client object
$client = new SRPC_Client($remove_url);
$client->debug=true;
// Run a query for PHP
if (!$client->call("http://feed.feedsky.com/fallseir")) {
die('Something went wrong - '.$client->getErrorCode().' : '.$client->getErrorMessage());
}

// Display the result
echo '
';
print_r($client->headers);
print_r($client->contents);
echo '
';

class SRPC_Client{
var $server;
var $port;
var $path;
var $useragent;
var $debug;
var $error;

var $contents;
var $headers;
function SRPC_Client($server, $path = false, $port = 80) {
if (!$path) {
// Assume we have been given a URL instead
$bits = parse_url($server);
$this->server = $bits['host'];
$this->port = isset($bits['port']) ? $bits['port'] : 80;
$this->path = isset($bits['path']) ? $bits['path'] : '/';
// Make absolutely sure we have a path
if (!$this->path) {
$this->path = '/';
}
} else {
$this->server = $server;
$this->path = $path;
$this->port = $port;
}
$this->useragent = 'The simple RPC PHP Library';
}
function Call($content){
$r="\r\n";
$length=strlen($content);
$request = "POST {$this->path} HTTP/1.0$r";
$request .= "Host: {$this->server}$r";
$request .= "Content-Type: text/xml charset=utf-8$r";
$request .= "User-Agent: {$this->useragent}$r";
$request .= "Content-length: {$length}$r$r";
$request .= $content;
// Now send the request
if ($this->debug) {
echo '
'.htmlspecialchars($request)."\n
\n\n";
}
$fp = @fsockopen($this->server, $this->port);
if (!$fp) {
$this->error = array(-32300, 'transport error - could not open socket');
return false;
}
fputs($fp, $request);
$contents = '';
$gotFirstLine = false;
$gettingHeaders = true;
$headers = '';
while (!feof($fp)) {
$line = fgets($fp, 4096);
if (!$gotFirstLine) {
// Check line for '200'
if (strstr($line, '200') === false) {
$this->error = array(-32300, 'transport error - HTTP status code was not 200');
return false;
}
$gotFirstLine = true;
}
if (trim($line) == '') {
$gettingHeaders = false;
}
if (!$gettingHeaders) {
$contents .= trim($line).$r;
}else{
$rawheaders .= trim($line).$r;
}
}
fclose($fp);
if ($this->debug) {
echo '
'.htmlspecialchars($contents)."\n
\n\n";
}

preg_match_all('/(.*?): (.*)\r/', $rawheaders, $matches);
$count = count($matches[1]);
for ( $i = 0; $i < $count; $i++) {
$key = strtolower($matches[1][$i]);
$headers["$key"] = $matches[2][$i];
}
preg_match('/.*([0-9]{3}).*/', $rawheaders, $return);
$headers['response'] = $return[1]; // HTTP response code eg 204, 200, 404
$code = $headers['response'];
/** if ( ('302' == $code || '301' == $code) && isset($headers['location']) ) **/
$this->rawheaders=$rawheaders;
$this->headers=$headers;
$this->contents=$contents;
return true;
}
}

1 条评论:

China Blogger 说...

你好!

我做了一个中文的blogger交流网站!欢迎你访问!http://findyou.blogspot.com/!也欢迎你贴帖子和留言!

我们很想找到你!
另外我可能把你的网址贴在帖子里推荐给大家,你不反对吧?
如果可以的话也希望你把我的网址贴在Blogger上好吗?