使用 PHP + socket 模拟发送 HTTP GET 请求,过程是:
① 打开连接
② 构造 GET 请求的数据:写入请求行、请求头信息、请求主体信息(GET 请求没有主体信息)
③ 发送 GET 请求
④ 读取(响应)
⑤ 关闭连接
【例】PHP + socket 编程,发送 GET 请求
<?php /* PHP + socket 编程 @发送 HTTP GET 请求 */ //http 请求类的接口 interface Proto{ //连接 url function conn($url); //发送 GET 请求 function get(); //发送 POST 请求 function post(); //关闭连接 function close(); } class Http implements Proto{ //换行符 const CRLF = "\r\n"; //fsocket 的错误号与错误描述 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->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(); return $this->response; } //构造 POST 请求的数据 public function post(){ } //发送请求 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); } //关闭连接 $this->close(); } //关闭连接 public function close(){ } } $url = ‘http://book.douban.com/subject/26376603/‘; $http = new Http($url); echo $http->get();
执行代码,输出:
图1
图2 响应信息
时间: 2024-10-11 10:30:23