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 响应信息

     

  • 相关阅读:
    简单的REST的框架实现
    将 Shiro 作为一个许可为基础的应用程序 五:password加密/解密Spring应用
    Java自注三进入
    hdu 4803 贪心/思维题
    SSH框架总结(框架分析+环境搭建+实例源代码下载)
    Rational Rose 2007 &amp;Rational Rose 2003 下载及破解方法和汉化文件下载
    hdu 5014 思维题/推理
    电脑蓝屏出现事件7000
    大豆生物柴油驱动的大巴斯(Bus)
    POJ 3481 &amp; HDU 1908 Double Queue (map运用)
  • 原文地址:https://www.cnblogs.com/dee0912/p/4638477.html
Copyright © 2011-2022 走看看