使用Telnet模拟Http请求
打开cmd运行框,输入Telnet www.baidu.com 80后按回车键。此时看到的界面是黑屏状态,标题栏显示 Telnet www.baidu.com
如果提示telnet不是内部或外部命令
可以参考百度经验。利用快捷键打开“Ctrl+]
”打开Telnet回显,按回车键后可以进入编辑状态。
回显模式:
编辑模式:
接下来是考验手速的时候了,单身党一定完胜的游戏。输入GET /index.html HTTP/1.1按回车键,接着输入HOST:www.baidu.com,连续按两次回车键(两次回车代表提交请求)输入速度不够快的话,将会连接失败。可以将代码写入记事本,使用时直接复制就好了。
然后来看看服务器的返回数据:
PHP模拟HTTP请求
Http.class.php
<?php
class HttpRequest
{
private $_host; //主机地址
private $_port; //端口号
private $_requestHead; //请求头信息
private $_requestMethod; //请求方式
private $_requestPath; //请求路径
private $_requestContent = ''; //请求正文
private $_httpVersion = '1.1'; //协议版本
/**
* [__contruction 初始化成员属性]
* @author:JieJie
*/
public function __construct($host,$port,$method,$path)
{
$this->_host = $host;
$this->_port = $port;
$this->_requestMethod = strtoupper($method);
$this->_requestPath = $path;
}
/**
* [setRequestHead 设置请求头信息]
* @author:JieJie
* @DateTime:2016-11-25T00:22:04+0800
* @param [array] $data [头信息数组]
*/
public function setRequestHead($data) {
foreach ($data as $key => $value) {
$this->_requestHead .= $key.':'.$value."\r\n";
}
$this->_requestHead .= "\r\n";
return $this;
}
/**
* [setRequestContent 设置请求正文]
* @author:JieJie
* @DateTime:2016-11-25T00:37:53+0800
* @param [array] $data
*/
public function setRequestContent($data) {
if($this->_requestMethod != 'POST')
return $this;
foreach ($data as $key => $value) {
$this->_requestContent .= "{$key}={$value}&";
}
$this->_requestContent = rtrim($this->_requestContent,'&')."\r\n";
return $this;
}
/**
* [sendRequest 发送HTTP请求并获取结果]
* @author:JieJie
* @DateTime:2016-11-25T00:51:53+0800
*/
public function sendRequest() {
//拼接请求行
$http = "{$this->_requestMethod} {$this->_requestPath} HTTP/{$this->_httpVersion}\r\n";
//拼接请求头
$http .= $this->_requestHead;
//拼接请求正文
$http .= $this->_requestContent;
//创建连接
$fp = fsockopen($this->_host,$this->_port,$errno,$errstr);
if(!$fp)
throw new Exception($errstr);
//发送请求
fwrite($fp, $http);
//获得结果
$result = '';
while (!feof($fp))
$result .= fgets($fp);
return $result;
}
}
?>
client.php
<?php
include './Http.class.php';
$Http = new HttpRequest('www.jiejieyh.cn','80','POST','/login.php');
$requestHead = [
'Host'=>'www.jiejieyh.cn',
'User-Agent'=>'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0',
'Accept'=>'application/json, text/javascript, */*; q=0.01',
'Accept-Language'=>'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding'=>'gzip, deflate',
'Content-Type'=>'application/x-www-form-urlencoded;',
'charset'=>'UTF-8',
'X-Requested-With'=>'XMLHttpRequest',
'Referer'=>'http://www.jiejieyh.cn',
'Content-Length'=>47,
'Connection'=>'keep-alive'
];
$requestContent = [
'password' => 'admin',
'username' => '123456',
];
$result = $Http->setRequestHead($requestHead)->setRequestContent($requestContent)->sendRequest();
echo $result;
?>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。