標籤:

sockets編程 發送http請求

<?php/* socket.class編程 發送http請求 *///模擬下載,註冊,登錄protected $line = array(); //請求行 const CRLF = "
"; //換行符 protected $header = array(); //請求頭信息 protected $body = array(); //主體信息 protected $version = "HTTP/1.1"; protected $fh = null; protected $url = array(); protected $errno = -1; protected $errstr = ""; protected $response = ""; //構造函數,進行初始化 public function __construct($url){ $this->conn($url);//連接 //設置頭信息 $this->setHeader("Host: " .$this->url["host"]); } /** * 此方法負責寫請求行 請求方法 請求路徑 協議 * @param string $method 請求方法 */ protected function setLine($method){ $this->line[0] = $method . " " .$this->url["path"] . " ".$this->version; } /** * 此方法負責寫頭信息 Host:localhost * @param string $headLine 頭信息 */ protected function setHeader($headLine){ $this->header[] = $headLine; } //此方法負責寫主體信息 protected function setBody(){ } //連接url public function conn($url){ //解析出地址 $this->url = parse_url($url); //判斷埠 if(!isset($this->url["port"])){ $this->url["port"] = "80"; } // 判斷query if(!isset($this->url["query"])) { $this->url["query"] = ""; } //fsockopen($hostname,$port,$errno,$errstr,$time) //參數對應的是:主機,埠,錯誤號,錯誤內容,時間間隔 $this->fh = fsockopen($this->url["host"],$this->url["port"],$this->errno,$this->errstr,3); } //構造ge請求的t查詢 public function get(){ $this->setLine("GET"); $this->response(); return $this->response; } //構造post請求的數據// 構造post查詢的數據 public function post($body = array()) { $this->setLine("POST"); // 設計content-type $this->setHeader("Content-type: application/x-www-form-urlencoded"); // 設計主體信息,比GET不一樣的地方 $this->setBody($body); // 計算content-length $this->setHeader("Content-length: " . strlen($this->body[0])); $this->request(); return $this->response; } //真正請求 public function response(){ //將請求行 頭信息,實體信息,放在一個數組裡,便於拼接 $req = array_merge($this->line,$this->header,array(" "),$this->body,array(" ")); $req = implode(self::CRLF,$req); echo $req;exit; fwrite($this->fh, $req); while(!feof($this->fh)){ $this->response .= fread($this->fh, 10); } $this->close(); //關閉連接 } public function close(){ fclose($this->fh); } $url = "http://mil.news.sina.com.cn/jssd/2017-08-25/doc-ifykkfas7750531.shtml"; $http = new Socket($url); $res = $http->get(); print_r($res);
推薦閱讀:

【序】一個關於量子計算的小專欄
設計模式及最佳實踐
0基礎學Python之九:循環語句(下)
NX8.0三軸銑數控加工編程
Leetcode Solutions(一) two-sum

TAG:編程 |