发送GET请求以及响应信息如下图所示:
本文实现了PHP+Socket实现了发送GET并显示响应结果。
【请求原理】:
1. 连接某URL的80端口打开
2. 发送头信息(写)
3. 读取网页内容
Socket操作远程文件和读取本地文件一样,把本地文件看成硬件传输,远程文件通过网络传输。
【代码实现】:
<span style="font-family:KaiTi_GB2312;font-size:14px;"><?PHP
/*
PHP + Socket编程 发送HTTP请求
*/
//http请求类的接口
interface Proto{
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Httpimplements Proto{
//定义一个回车换行,在Linux下是'\n' 在windows下是'\r\n'
//HTTP标准是'\r\n'
const CRLF = "\r\n";
protected $errno = -1;
protected $errstr = '';
protected $response = '';
protected $url = null;
protected $fh = null;
protected $version = 'HTTP/1.1';
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->version;
}
//此方法负责写头信息
protected function setHeader($headerline){
$this -> header[] = $headerline;
}
//此方法负责写主体信息
protected function setBody(){
}
//连接url
public function conn($url){
$this -> url = parse_url($url);
//判断端口
if(!isset($this->url['port'])){
$this -> url['port'] = 80;
}
$this -> fh =fsockopen($this -> url['host'],$this -> url['port'],$this ->errno,$this-> errstr,3);
}
//构造get请求数据
public function get(){
$this -> setLine('GET');
$this -> request();
}
//构造post请求数据
public function post(){
}
//发送GET请求
public function request(){
//把请求行,头信息,实体信息放在一个数组里,便于拼接。
$req = array_merge($this -> line,$this-> header,array(''),$this -> body,array(''));
$req = implode(self::CRLF,$req);
// echo $req;
fwrite($this->fh,$req);
while(!feof($this->fh)){
$this -> response .=fread($this->fh,1024);
}
echo $this -> response;
$this -> close();//关闭连接
}
//关闭连接
public function close(){
}
}
$url ='http://localhost/test.php';
$http = newHttp($url);
$http -> get();</span>
其中注意的几个问题:
1.在测试时,如果发现提示如下错误:
这是没有设置端口的原因,只需要判断一下端口就可以了。
<span style="font-family:KaiTi_GB2312;font-size:14px;">//判断端口
if(!isset($this->url['port'])){
$this -> url['port'] = 80;
}
$this -> fh =fsockopen($this -> url['host'],$this -> url['port'],$this ->errno,$this-> errstr,3);</span>
【运行结果】:
抓下包:
实现完毕。