php 利用socket發(fā)送HTTP請(qǐng)求(GET,POST)
今天給大家?guī)?lái)的是如何利用socket發(fā)送GET,POST請(qǐng)求。我借用燕十八老師封裝好的一個(gè)Http類(lèi)給進(jìn)行說(shuō)明。
在日常編程中相信很多人和我一樣大部分時(shí)間是利用瀏覽器向服務(wù)器提出GET,POST請(qǐng)求,那么可否利用其它方式提出GET,POST請(qǐng)求呢?答案必然是肯定的。了解過(guò)HTTP協(xié)議的人知道,瀏覽器提交請(qǐng)求的實(shí)質(zhì)是向服務(wù)器發(fā)送一個(gè)請(qǐng)求信息,這個(gè)請(qǐng)求信息有請(qǐng)求行,請(qǐng)求頭,請(qǐng)求體(非必須)構(gòu)成。服務(wù)器根據(jù)請(qǐng)求信息返回一個(gè)響應(yīng)信息。連接斷開(kāi)。
HTTP請(qǐng)求的格式如下所示:
<request-line> <headers> <blank line> [<request-body>]
HTTP響應(yīng)的格式與請(qǐng)求的格式十分相似:
<status-line> <headers> <blank line> [<response-body>]
我們可以利用HTTP發(fā)送請(qǐng)求的原理,可以重新考慮利用socket發(fā)送HTTP請(qǐng)求。
Socket的英文原義是“孔”或“插座”。通常也稱(chēng)作“套接字”,用于描述IP地址和端口,是一個(gè)通信鏈的句柄,可以用來(lái)實(shí)現(xiàn)不同虛擬機(jī)或不同計(jì)算機(jī)之間的通信。在Internet上的主機(jī)一般運(yùn)行了多個(gè)服務(wù)軟件,同時(shí)提供幾種服務(wù)。每種服務(wù)都打開(kāi)一個(gè)Socket,并綁定到一個(gè)端口上,不同的端口對(duì)應(yīng)于不同的服務(wù)。如此看來(lái),其實(shí)利用socket操作遠(yuǎn)程文件和讀寫(xiě)本地的文件一樣容易,把本地文件看成通過(guò)硬件傳輸,遠(yuǎn)程文件通過(guò)網(wǎng)線傳輸就行了。
因而可以將發(fā)送請(qǐng)求的考慮成 建立連接->打開(kāi)socket接口(fsockopen())->寫(xiě)入請(qǐng)求(fwrite())->讀出響應(yīng)(fread()->關(guān)閉文件(fclose())。話(huà)不多說(shuō),直接上代碼:
<?php
interface Proto {
// 連接url
function conn($url);
//發(fā)送get查詢(xún)
function get();
// 發(fā)送post查詢(xún)
function post();
// 關(guān)閉連接
function close();
}
class Http implements Proto {
const CRLF = "\r\n";
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']);
}
// 此方法負(fù)責(zé)寫(xiě)請(qǐng)求行
protected function setLine($method) {
$this->line[0] = $method . ' ' . $this->url['path'] . '?' .$this->url['query'] . ' '. $this->version;
}
// 此方法負(fù)責(zé)寫(xiě)頭信息
public function setHeader($headerline) {
$this->header[] = $headerline;
}
// 此方法負(fù)責(zé)寫(xiě)主體信息
protected function setBody($body) {
$this->body[] = http_build_query($body);
}
// 連接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'] = '';
}
$this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,3);
}
//構(gòu)造get請(qǐng)求的數(shù)據(jù)
public function get() {
$this->setLine('GET');
$this->request();
return $this->response;
}
// 構(gòu)造post查詢(xún)的數(shù)據(jù)
public function post($body = array()) {
$this->setLine('POST');
// 設(shè)計(jì)content-type
$this->setHeader('Content-type: application/x-www-form-urlencoded');
// 設(shè)計(jì)主體信息,比GET不一樣的地方
$this->setBody($body);
// 計(jì)算content-length
$this->setHeader('Content-length: ' . strlen($this->body[0]));
$this->request();
return $this->response;
}
// 真正請(qǐng)求
public function request() {
// 把請(qǐng)求行,頭信息,實(shí)體信息 放在一個(gè)數(shù)組里,便于拼接
$req = array_merge($this->line,$this->header,array(''),$this->body,array(''));
//print_r($req);
$req = implode(self::CRLF,$req);
//echo $req; exit;
fwrite($this->fh,$req);
while(!feof($this->fh)) {
$this->response .= fread($this->fh,1024);
}
$this->close(); // 關(guān)閉連接
}
// 關(guān)閉連接
public function close() {
fclose($this->fh);
}
}
利用此類(lèi)發(fā)送一個(gè)簡(jiǎn)單的GET請(qǐng)求:
<?php //記得引用Http類(lèi) $url="http://home.jb51.net/u/DeanChopper/"; $http=new Http($url); $response=$http->get(); print_r($response);
返回值為信息,可以對(duì)響應(yīng)信息進(jìn)行進(jìn)一步處理,得到自己想得到的內(nèi)容。
我們來(lái)看下一個(gè)具體的實(shí)例
<?php
/**
* 使用PHP Socket 編程模擬Http post和get請(qǐng)求
* @author koma
*/
class Http{
private $sp = "\r\n"; //這里必須要寫(xiě)成雙引號(hào)
private $protocol = 'HTTP/1.1';
private $requestLine = "";
private $requestHeader = "";
private $requestBody = "";
private $requestInfo = "";
private $fp = null;
private $urlinfo = null;
private $header = array();
private $body = "";
private $responseInfo = "";
private static $http = null; //Http對(duì)象單例
private function __construct() {}
public static function create() {
if ( self::$http === null ) {
self::$http = new Http();
}
return self::$http;
}
public function init($url) {
$this->parseurl($url);
$this->header['Host'] = $this->urlinfo['host'];
return $this;
}
public function get($header = array()) {
$this->header = array_merge($this->header, $header);
return $this->request('GET');
}
public function post($header = array(), $body = array()) {
$this->header = array_merge($this->header, $header);
if ( !empty($body) ) {
$this->body = http_build_query($body);
$this->header['Content-Type'] = 'application/x-www-form-urlencoded';
$this->header['Content-Length'] = strlen($this->body);
}
return $this->request('POST');
}
private function request($method) {
$header = "";
$this->requestLine = $method.' '.$this->urlinfo['path'].'?'.$this->urlinfo['query'].' '.$this->protocol;
foreach ( $this->header as $key => $value ) {
$header .= $header == "" ? $key.':'.$value : $this->sp.$key.':'.$value;
}
$this->requestHeader = $header.$this->sp.$this->sp;
$this->requestInfo = $this->requestLine.$this->sp.$this->requestHeader;
if ( $this->body != "" ) {
$this->requestInfo .= $this->body;
}
/*
* 注意:這里的fsockopen中的url參數(shù)形式為"www.xxx.com"
* 不能夠帶"http://"這種
*/
$port = isset($this->urlinfo['port']) ? isset($this->urlinfo['port']) : '80';
$this->fp = fsockopen($this->urlinfo['host'], $port, $errno, $errstr);
if ( !$this->fp ) {
echo $errstr.'('.$errno.')';
return false;
}
if ( fwrite($this->fp, $this->requestInfo) ) {
$str = "";
while ( !feof($this->fp) ) {
$str .= fread($this->fp, 1024);
}
$this->responseInfo = $str;
}
fclose($this->fp);
return $this->responseInfo;
}
private function parseurl($url) {
$this->urlinfo = parse_url($url);
}
}
// $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html";
$url = "http://localhost/httppro/post.php";
$http = Http::create()->init($url);
/* 發(fā)送get請(qǐng)求
echo $http->get(array(
'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
));
*/
/* 發(fā)送post請(qǐng)求 */
echo $http->post(array(
'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
), array('username'=>'發(fā)一個(gè)中文', 'age'=>22));
- PHP中$GLOBALS[''HTTP_RAW_POST_DATA'']和$_POST的區(qū)別分析
- PHP中Http協(xié)議post請(qǐng)求參數(shù)
- 使用PHP Socket 編程模擬Http post和get請(qǐng)求
- php中運(yùn)用http調(diào)用的GET和POST方法示例
- PHP實(shí)現(xiàn)支持GET,POST,Multipart/form-data的HTTP請(qǐng)求類(lèi)
- php中用socket模擬http中post或者get提交數(shù)據(jù)的示例代碼
- php獲取通過(guò)http協(xié)議post提交過(guò)來(lái)xml數(shù)據(jù)及解析xml
- PHP使用Http Post請(qǐng)求發(fā)送Json對(duì)象數(shù)據(jù)代碼解析
相關(guān)文章
PHP基于openssl實(shí)現(xiàn)非對(duì)稱(chēng)加密代碼實(shí)例
這篇文章主要介紹了PHP基于openssl實(shí)現(xiàn)非對(duì)稱(chēng)加密代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
PHP通過(guò)iconv將字符串從GBK轉(zhuǎn)換為UTF8字符集
PHP通過(guò)iconv將字符串從GBK轉(zhuǎn)換為UTF8字符集的方法,需要的朋友可以參考下。2011-07-07
PHP基于openssl實(shí)現(xiàn)的非對(duì)稱(chēng)加密操作示例
這篇文章主要介紹了PHP基于openssl實(shí)現(xiàn)的非對(duì)稱(chēng)加密操作,結(jié)合實(shí)例形式分析了openssl安裝、密鑰生成及php基于openssl的非對(duì)稱(chēng)加密算法相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
php實(shí)現(xiàn)的遍歷文件夾下所有文件,編輯刪除
遍歷文件夾; 功能:(a)可刪除文件 (b)可編輯文本,網(wǎng)頁(yè)文件 (c)可刪除文件夾,前提是該文件夾為空 (d)可建立文件,文件夾,修改文件夾名稱(chēng)2010-01-01
PHP轉(zhuǎn)盤(pán)抽獎(jiǎng)接口實(shí)例
這篇文章主要介紹了PHP轉(zhuǎn)盤(pán)抽獎(jiǎng)接口的實(shí)現(xiàn)方法,實(shí)例分析了隨機(jī)抽獎(jiǎng)接口的實(shí)現(xiàn)原理與對(duì)應(yīng)數(shù)據(jù)庫(kù)操作的技巧,需要的朋友可以參考下2015-02-02
PHP實(shí)現(xiàn)刪除多重?cái)?shù)組對(duì)象屬性并重新賦值的方法
這篇文章主要介紹了PHP實(shí)現(xiàn)刪除多重?cái)?shù)組對(duì)象屬性并重新賦值的方法,涉及php結(jié)合sphinx操作數(shù)組元素的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-06-06
php中用socket模擬http中post或者get提交數(shù)據(jù)的示例代碼
以下是對(duì)php中用socket模擬http中post或者get提交數(shù)據(jù)的示例代碼進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08

