fsockopen实现的HTTP请求
来源:互联网 发布:四川省六有大数据平台 编辑:程序博客网 时间:2024/05/06 09:36
1.get方式,code来自于PHP手册:
<?php
$url='/new.php'.'?'.urlencode(id).'='.urlencode(88);
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />/n";
} else {
$out = "GET / HTTP/1.1/r/n";
$out .= "Host: www.example.com/r/n";
$out .= "Connection: Close/r/n/r/n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
//上面的code可以模拟浏览器www.example.com/new.php?id=88
2.post方式:
<?php
$host='www.example.com';
$url='/login.php';
$data=urlencode(username).'='.urlencode($username).urlencode(password).'='.urlencode($password);
$fp=fsockopen("www.baidu.com",80,$errno,$errstr,30);
if (!$fp) {
echo "$errstr ($errno)<br />/n";
} else {
$out = "POST ".$url." HTTP/1.1/r/n";
$out .= "Host: www.example.com/r/n";
$out .= "Content-type: application/x-www-form-urlencoded/r/n";
$out .= "Content-Length: ".$data."/r/n";
$out .= "Connection: Close/r/n/r/n";
$out .=$data;
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
?>
//上面的code可以模拟用户登录www.example.com/login.php
3.get与post的异同:
-------------------------------------------------
HTTP请求报文:request-line
headers (0或有多个)
/***headers***/
//name1: content
//name2: content
//.....
/***headers***/
<blank line>
body (只对POST请求有效)
-------------------------------------------------
HTTP响应报文:status-line
headers (0或有多个)
/***headers***/
//name1: content
//name2: content
//.....
/***headers***/
<blank line>
body (只对POST请求有效)
-------------------------------------------------
从上面的报文格式可以看出,header之间的区分是换行"/r/n",header于body的区分是空白行,这就算为什么上面get、post最后都有"Connection: Close/r/n/r/n"原因。
get请求的url要经过urlencode编码,这就像浏览器的请求时看到的%23%23的一样,post请求的内容也要经过urlencode编码。
POST请求必需在header中加入"Content-type: application/x-www-form-urlencoded/r/n"和"Content-Length: ".$data."/r/n",post提交的数据要在"Connection: Close/r/n/r/n"之后发送,因为该数据相当请求的内容是在header之后的.
4.解析响应报文
也许我们只关心报文的头或者body,在报文格式中我们看到header于body的区分是空白行的。
$headers = "";
while ($str = trim(fgets($sock,4096)))
$headers .= "$str/n";
$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);
fclose($sock);
$this->responseText=$body;
//通过上面的代码就可以将header于body分开
字符串为空时(即空白行)其bool值为false,这样就把header与body分开了。
BTW-参考资料:《TCP/IP详解》卷三13章HTTP
HTTPClient类:http://scripts.incutio.com/httpclient/
- fsockopen实现的HTTP请求
- php fsockopen实现异步请求
- 整理 fsockopen 请求实现方式
- Php 使用 fsockopen发送http请求
- 利用fsockopen模拟HTTP发送请求
- php中使用fsockopen实现异步请求
- fsockopen发请求
- http同步请求的实现
- HTTP协议 fsockopen模拟请求代理端发送get post请求 curl基本使用
- 用PHP fsockopen写的HTTP下载的类
- PHP利用fsockopen POST HTTP请求(URL)并获取返回值
- fsockopen 模拟 post get 请求
- php fsockopen多线程实现
- 用PHP的Socket实现HTTP请求
- PHP curl实现异步的http请求
- java实现HTTP协议的请求
- Java实现HTTP协议的请求
- 基于HTTP请求处理器流程的实现 .
- js操作css float属性
- 学习makefile
- 计算机世界:“XXXX”腾讯
- IE6双空白边bug
- firefox下绝对定位元素重叠造成不可点击问题
- fsockopen实现的HTTP请求
- 深入Java关键字null
- 将UDT的数据拉平
- Webwork/Struts2 Tree标签(树形控件)的使用
- SyncML简介
- 常用小代码
- c++简单链表实现
- SEO的关键词分析
- DM642 FVID驱动编写小结