socket编程发送GET请求

来源:互联网 发布:程序员 白发老头图片 编辑:程序博客网 时间:2024/06/08 12:07
<?php/* * PHP + socket 编程   运用GET方法模拟一下发送HTTP请求 *///http请求类的接口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;        //url数组    protected $fh = null;    protected $version = 'HTTP/1.1';   //HTTP协议名称   protected $line = array();    //请求行   protected $header = array();  //头信息   protected $body = array();    //主体信息   //调用公共函数    public  function __construct($url){       $this->conn($url);      //分析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(''));//    print_r($req);      $req = implode($req,self::CRLF);//    echo $req;      fwrite($this->fh,$req);      while (!feof($this->fh)) {    //之要不到结尾就一直读         $this->response.= fread($this->fh,1024);      }      $this->close();   //关闭连接   }   //关闭连接protected   function close(){   }   }$url = 'http://news.163.com/16/1011/08/C336UQQV00014PRF.html';$http = new Http($url);echo $http->get();//print_r($http);//$http->request();?>
0 0
原创粉丝点击