fsockopen实现的HTTP请求

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/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值