越简单越好!

用PHP的Socket实现HTTP请求

bevin 发表于 2009-08-18 15:33 | 16次阅读 0次推荐   PHP

<?php
class HttpRequest
{
var $sHostAdd;
var $sUri;
var $iPort;

var $sRequestHeader;

var $sResponse;

function HttpRequest($sUrl)
{
   $sPatternUrlPart = '/http://([a-z-.0-9]+)(:(d+)){0,1}(.*)/i';
   $arMatchUrlPart = array();
   preg_match($sPatternUrlPart, $sUrl, $arMatchUrlPart);
  
   $this->sHostAdd = gethostbyname($arMatchUrlPart[1]);
   if (empty($arMatchUrlPart[4]))
   {
    $this->sUri = '/';
   }
   else
   {
    $this->sUri = $arMatchUrlPart[4];
   }
   if (empty($arMatchUrlPart[3]))
   {
    $this->iPort = 80;
   }
   else
   {
    $this->iPort = $arMatchUrlPart[3];
   }
  
   $this->addRequestHeader('Host: '.$arMatchUrlPart[1]);
   $this->addRequestHeader('Connection: Close');
}

function addRequestHeader($sHeader)
{
   $this->sRequestHeader .= trim($sHeader)." ";
}

function sendRequest($sMethod = 'GET', $sPostData = '')
{
   $sRequest = $sMethod." ".$this->sUri." HTTP/1.1 ";
   $sRequest .= $this->sRequestHeader;
   if ($sMethod == 'POST')
   {
    $sRequest .= "Content-Type: application/x-www-form-urlencoded ";
    $sRequest .= "Content-Length: ".strlen($sPostData)." ";
    $sRequest .= " ";
    $sRequest .= $sPostData." ";
   }
   $sRequest .= " ";
  
   $sockHttp = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
   if (!$sockHttp)
   {
    die('socket_create() failed!');
   }
  
   $resSockHttp = socket_connect($sockHttp, $this->sHostAdd, $this->iPort);
   if (!$resSockHttp)
   {
    die('socket_connect() failed!');
   }
  
   socket_write($sockHttp, $sRequest, strlen($sRequest));
  
   $this->sResponse = '';
   while ($sRead = socket_read($sockHttp, 4096))
   {
    $this->sResponse .= $sRead;
   }
  
   socket_close($sockHttp);
}

function getResponse()
{
   return $this->sResponse;
}

function getResponseBody()
{
   $sPatternSeperate = '/ /';
   $arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);
   return $arMatchResponsePart[1];
}

function getResponseHead()
{
   $sPatternSeperate = '/ /';
   $arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);
   return $arMatchResponsePart[0];
}
}

$bevin = new HttpRequest('http://chenapp.com/?a=b');
$bevin->sendRequest('POST','a=b');
$result = $bevin->getResponse();
echo $result;
?>

+0
发表评论
×您的大名会显示在评论处

评论内容不能少于5个字哦~~~

评论列表
当前暂无评论
发送数据中... 请求错误. 请输入评论内容和验证码后再发布 您已经参与过了,谢谢
返回顶部 ^