zoukankan      html  css  js  c++  java
  • HTTP 笔记与总结(3 )socket 编程:发送 GET 请求

    使用 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 = "
    ";
    
    	//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 响应信息

     

  • 相关阅读:
    Thrift安装编译指南
    Linux磁盘与文件系统管理
    你懂得C,所以C++也不在话下
    加速NFV(网络功能虚拟化)数据面:SR-IOV和DPDK[原文意译]
    十张图看懂SDN与NFV的区别与联系?
    Lambda表达式用法
    论文写作+gnuplot制图
    私钥、公钥、数字签名和数字证书
    synchronized和Lock的异同
    介绍HTTP协议的传输过程
  • 原文地址:https://www.cnblogs.com/dee0912/p/4638477.html
Copyright © 2011-2022 走看看