http協議(2)

學習資源:燕十八的http課程(公開形式的資源,請自行查找)  二三節


我的筆記:

面向對象

新建一個http請求類,實現自定義接口Proto

在http類中重新實現方法

主要是通過fsockopen打開socket,然後從socket中讀取網頁資源,寫入字符串中,再echo出來,具體的響應體可以通過查看源代碼來獲知

<?php
//http請求類接口
interface Proto{
	//連接url
	function conn($url);
	//發送GET請求
	function get();
	//發送POST請求
	function post();
	//關閉連接
	function close();
}

class Http implements Proto{
	const CRLF = "\r\n";//carriage return line feed
	protected $url = array();
	protected $line = array();
	protected $header = array();
	protected $body = array();
	protected $fh = null;
	protected $version = 'HTTP/1.1';
	protected $errno = -1;
	protected $errstr = '';
	protected $response = '';
	public function __construct($url)
	{
		$this->conn($url);
		$this->setHeader("Host:".$this->url["host"]);
	}
    //此方法負責寫請求行
	protected function setLine($method){
		$this->line[] = $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(){
		//把請求行和body信息放在一個數組中,便於拼接
		$req = array_merge($this->line,$this->header,array(''),$this->body,array(''));
		
		$req = implode(self::CRLF, $req);
		//print_r($req);
		fwrite($this->fh,$req);
		while(!feof($this->fh)){
			$this->response.=fread($this->fh,1024);
		}
		$this->close();//關閉連接
	}
	//關閉連接
	public function close(){

	}
}

$url = "http://news.163.com/16/0317/20/BICRPR0400014PRF.html";
$http = new http($url);
echo $http->get();
//print_r($http);
//$http->request();


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章