类
<?php
interface Proto{
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Http implements Proto{
const CRLF="\r\n";
protected $errno=-1;
protected $errstr='';
protected $response='';
protected $url=null;
protected $version='HTTP/1.1';
protected $fh=null;
protected $line=array();
protected $header=array();
protected $body=array();
public function __construct($url){
$this->conn($url);
$this->setHeader('Host:'.$this->url['host']);
}
//此方法负责写请求行
protected function setLine($method){
$this->line[0]=$method.' '.$this->url['path'].'?'.$this->url['query'].' '.$this->version;
}
//此方法负责写头信息
public function setHeader($headerline){
$this->header[]=$headerline;
}
//此方法负责写主体信息
protected function setBody($body){
$this->body[]=http_build_query($body);;
}
//连接url
function conn($url){
$this->url=parse_url($url);
//判断端口
if($this->url['scheme']=='https')
{
$this->url['port']=443;
$urlhost="ssl://".$this->url['host'];
}
else
{
if(!isset($this->url['port']))
{
$this->url['port']=80;
$urlhost=$this->url['host'];
}
}
$this->fh=fsockopen($urlhost,$this->url['port'],$this->errno,$this->errstr,3) or exit($this->errno.$this->errstr);
}
//构造get请求的数据
function get(){
$this->setLine('GET');
$this->request();
return $this->response;
}
//构造post请求的数据
function post($body=array()){
//构造主体信息
$this->setLine('POST');
//设置content-type
$this->setHeader('Content-type:application/x-www-form-urlencoded');
//设置主体信息,比GET不一样的地方
$this->setBody($body);
//计算content-length
$this->setHeader('Content-length:'.strlen($this->body[0]));
$this->request();
return $this->response;
}
//真正请求
function request(){
//把请求行,头信息,实体信息 放在一个数组里,便于拼接
$req=array_merge($this->line,$this->header,array(''),$this->body,array(''));
$req=implode(self::CRLF,$req);
// print_r($this);
// echo $req;
// exit;
fwrite($this->fh,$req);
while(!feof($this->fh)){
stream_set_timeout($this->fh, 1);
$this->response.=fread($this->fh,1024);
$info = stream_get_meta_data($this->fh);
if ($info['timed_out']) {
break;
}
}
$this->close();//关闭连接
return $this->response;
}
//关闭连接
function close(){
fclose($this->fh);
}
}
?>
调用
<?php
require('Http.class.php');
$url="";
$http=new Http($url);
//设置header
$http->setHeader('cookie:wqwqwq');
$content=$http->get();
?>
本文介绍了一个使用PHP实现的简单网络请求类,该类通过接口定义了连接URL、发送GET和POST请求的方法,并实现了这些功能。文章展示了如何创建类实例并进行网络请求。

487

被折叠的 条评论
为什么被折叠?



