PHP封装的HttpClient类用法实例


Posted in PHP onJune 17, 2015

本文实例讲述了PHP封装的HttpClient类。分享给大家供大家参考。具体分析如下:

这是一段php封装的HttpClient类,可实现GET POST Cookie Session等简单的功能。原来做过,这两天重新修改了一下。

<?php 
/* 
 * Filename: httpclient.php 
 * Created on 2012-12-21 
 * Created by RobinTang 
 * To change the template for this generated file go to 
 * Window - Preferences - PHPeclipse - PHP - Code Templates 
 */ 
class SinCookie { 
  public $name; // Cookie名称 
  public $value; // Cookie值 
  // 下面三个属性现在未实现 
  public $expires; // 过期时间 
  public $path; // 路径 
  public $domain; // 域 
  // 从Cookie字符串创建一个Cookie对象 
  function __construct($s = false) { 
    if ($s) { 
      $i1 = strpos($s, '='); 
      $i2 = strpos($s, ';'); 
      $this->name = trim(substr($s, 0, $i1)); 
      $this->value = trim(substr($s, $i1 +1, $i2 - $i1 -1)); 
    } 
  } 
  // 获取Cookie键值对 
  function getKeyValue() { 
    return "$this->name=$this->value"; 
  } 
} 
// 会话上下文 
class SinHttpContext { 
  public $cookies; // 会话Cookies 
  public $referer; // 前一个页面地址 
  function __construct() { 
    $this->cookies = array (); 
    $this->refrer = ""; 
  } 
  // 设置Cookie 
  function cookie($key, $val) { 
    $ck = new SinCookie(); 
    $ck->name = $key; 
    $ck->value = $val; 
    $this->addCookie($ck); 
  } 
  // 添加Cookie 
  function addCookie($ck) { 
    $this->cookies[$ck->name] = $ck; 
  } 
  // 获取Cookies字串,请求时用到 
  function cookiesString() { 
    $res = ''; 
    foreach ($this->cookies as $ck) { 
      $res .= $ck->getKeyValue() . ';'; 
    } 
    return $res; 
  } 
} 
// Http请求对象 
class SinHttpRequest { 
  public $url; // 请求地址 
  public $method = 'GET'; // 请求方法 
  public $host; // 主机 
  public $path; // 路径 
  public $scheme; // 协议,http 
  public $port; // 端口 
  public $header; // 请求头 
  public $body; // 请求正文 
  // 设置头 
  function setHeader($k, $v) { 
    if (!isset ($this->header)) { 
      $this->header = array (); 
    } 
    $this->header[$k] = $v; 
  } 
  // 获取请求字符串 
  // 包含头和请求正文 
  // 获取之后直接写socket就行 
  function reqString() { 
    $matches = parse_url($this->url); 
    !isset ($matches['host']) && $matches['host'] = ''; 
    !isset ($matches['path']) && $matches['path'] = ''; 
    !isset ($matches['query']) && $matches['query'] = ''; 
    !isset ($matches['port']) && $matches['port'] = ''; 
    $host = $matches['host']; 
    $path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/'; 
    $port = !empty ($matches['port']) ? $matches['port'] : 80; 
    $scheme = $matches['scheme'] ? $matches['scheme'] : 'http'; 
    $this->host = $host; 
    $this->path = $path; 
    $this->scheme = $scheme; 
    $this->port = $port; 
    $method = strtoupper($this->method); 
    $res = "$method $path HTTP/1.1\r\n"; 
    $res .= "Host: $host\r\n"; 
    if ($this->header) { 
      reset($this->header); 
      while (list ($k, $v) = each($this->header)) { 
        if (isset ($v) && strlen($v) > 0) 
          $res .= "$k: $v\r\n"; 
      } 
    } 
    $res .= "\r\n"; 
    if ($this->body) { 
      $res .= $this->body; 
      $res .= "\r\n\r\n"; 
    } 
    return $res; 
  } 
} 
// Http响应 
class SinHttpResponse { 
  public $scheme; // 协议 
  public $stasus; // 状态,成功的时候是ok 
  public $code; // 状态码,成功的时候是200 
  public $header; // 响应头 
  public $body; // 响应正文 
  function __construct() { 
    $this->header = array (); 
    $this->body = null; 
  } 
  function setHeader($key, $val) { 
    $this->header[$key] = $val; 
  } 
} 
// HttpClient 
class SinHttpClient { 
  public $keepcontext = true; // 是否维持会话 
  public $context; // 上下文 
  public $request; // 请求 
  public $response; // 响应 
  public $debug = false;
  // 是否在Debug模式,
  //为true的时候会打印出请求内容和相同的头部 
  function __construct() { 
    $this->request = new SinHttpRequest(); 
    $this->response = new SinHttpResponse(); 
    $this->context = new SinHttpContext(); 
    $this->timeout = 15; // 默认的超时为15s 
  } 
  // 清除上一次的请求内容 
  function clearRequest() { 
    $this->request->body = ''; 
    $this->request->setHeader('Content-Length', false); 
    $this->request->setHeader('Content-Type', false); 
  } 
  // post方法 
  // data为请求的数据 
  // 为键值对的时候模拟表单提交 
  // 其他时候为数据提交,提交的形式为xml 
  // 如有其他需求,请自行扩展 
  function post($url, $data = false) { 
    $this->clearRequest(); 
    if ($data) { 
      if (is_array($data)) { 
        $con = http_build_query($data); 
        $this->request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); 
      } else { 
        $con = $data; 
        $this->request->setHeader('Content-Type', 'text/xml; charset=utf-8'); 
      } 
      $this->request->body = $con; 
      $this->request->method = "POST"; 
      $this->request->setHeader('Content-Length', strlen($con)); 
    } 
    $this->startRequest($url); 
  } 
  // get方法 
  function get($url) { 
    $this->clearRequest(); 
    $this->request->method = "GET"; 
    $this->startRequest($url); 
  } 
  // 该方法为内部调用方法,不用直接调用 
  function startRequest($url) { 
    $this->request->url = $url; 
    if ($this->keepcontext) { 
      // 如果保存上下文的话设置相关信息 
      $this->request->setHeader('Referer', $this->context->refrer); 
      $cks = $this->context->cookiesString(); 
      if (strlen($cks) > 0) 
        $this->request->setHeader('Cookie', $cks); 
    } 
    // 获取请求内容 
    $reqstring = $this->request->reqString(); 
    if ($this->debug) 
      echo "Request:\n$reqstring\n"; 
    try { 
      $fp = fsockopen($this->request->host, $this->request->port, $errno, $errstr, $this->timeout); 
    } catch (Exception $ex) { 
      echo $ex->getMessage(); 
      exit (0); 
    } 
    if ($fp) { 
      stream_set_blocking($fp, true); 
      stream_set_timeout($fp, $this->timeout); 
      // 写数据 
      fwrite($fp, $reqstring); 
      $status = stream_get_meta_data($fp); 
      if (!$status['timed_out']) { //未超时 
        // 下面的循环用来读取响应头部 
        while (!feof($fp)) { 
          $h = fgets($fp); 
          if ($this->debug) 
            echo $h; 
          if ($h && ($h == "\r\n" || $h == "\n")) 
            break; 
          $pos = strpos($h, ':'); 
          if ($pos) { 
            $k = strtolower(trim(substr($h, 0, $pos))); 
            $v = trim(substr($h, $pos +1)); 
            if ($k == 'set-cookie') { 
              // 更新Cookie 
              if ($this->keepcontext) { 
                $this->context->addCookie(new SinCookie($v)); 
              } 
            } else { 
              // 添加到头里面去 
              $this->response->setHeader($k, $v); 
            } 
          } else { 
            // 第一行数据 
            // 解析响应状态 
            $preg = '/^(\S*) (\S*) (.*)$/'; 
            preg_match_all($preg, $h, $arr); 
            isset ($arr[1][0]) & $this->response->scheme = trim($arr[1][0]); 
            isset ($arr[2][0]) & $this->response->stasus = trim($arr[2][0]); 
            isset ($arr[3][0]) & $this->response->code = trim($arr[3][0]); 
          } 
        } 
        // 获取响应正文长度 
        $len = (int) $this->response->header['content-length']; 
        $res = ''; 
        // 下面的循环读取正文 
        while (!feof($fp) && $len > 0) { 
          $c = fread($fp, $len); 
          $res .= $c; 
          $len -= strlen($c); 
        } 
        $this->response->body = $res; 
      } 
      // 关闭Socket 
      fclose($fp); 
      // 把返回保存到上下文维持中 
      $this->context->refrer = $url; 
    } 
  } 
} 
// demo 
// now let begin test it 
$client = new SinHttpClient(); // create a client 
$client->get('http://www.baidu.com/');  // get 
echo $client->response->body; // echo 
?>

希望本文所述对大家的php程序设计有所帮助。

PHP 相关文章推荐
十天学会php(3)
Oct 09 PHP
树型结构列出指定目录里所有文件的PHP类
Oct 09 PHP
可以在线执行PHP代码包装修正版
Mar 15 PHP
php xml文件操作实现代码(二)
Mar 20 PHP
PHP 变量定义和变量替换的方法
Jul 30 PHP
php防注入,表单提交值转义的实现详解
Jun 10 PHP
PHP 5.3新增魔术方法__invoke概述
Jul 23 PHP
php数组添加元素方法小结
Dec 20 PHP
php如何执行非缓冲查询API
Jul 22 PHP
微信支付扫码支付php版
Jul 22 PHP
laravel框架实现后台登录、退出功能示例
Oct 31 PHP
php实现的简单多进程服务器类完整示例
Feb 01 PHP
PHP处理postfix邮件内容的方法
Jun 16 #PHP
PHP限制HTML内容中图片必须是本站的方法
Jun 16 #PHP
php采集中国代理服务器网的方法
Jun 16 #PHP
分享php分页的功能模块
Jun 16 #PHP
PHP生成plist数据的方法
Jun 16 #PHP
php动态绑定变量的用法
Jun 16 #PHP
php实现在服务器端调整图片大小的方法
Jun 16 #PHP
You might like
如何开始收听短波广播
2021/03/01 无线电
在php MYSQL中插入当前时间
2008/04/06 PHP
JoshChen_web格式编码UTF8-无BOM的小细节分析
2013/08/16 PHP
php代码审计比较有意思的例子
2014/05/07 PHP
PHP扩展迁移为PHP7扩展兼容性问题记录
2016/02/15 PHP
javascript cookie解码函数(兼容ff)
2008/03/17 Javascript
jquery异步跨域访问代码
2013/06/28 Javascript
常用js字符串判断方法整理
2013/10/18 Javascript
jQuery选择器简明总结(含用法实例,一目了然)
2014/04/25 Javascript
ANGULARJS中用NG-BIND指令实现单向绑定的例子
2014/12/08 Javascript
jquery 根据name名获取元素的value值
2015/02/27 Javascript
JS中处理时间之setUTCMinutes()方法的使用
2015/06/12 Javascript
通过js获取上传的图片信息(临时保存路径,名称,大小)然后通过ajax传递给后端的方法
2015/10/01 Javascript
jquery实现简单实用的弹出层效果代码
2015/10/15 Javascript
Angular中$compile源码分析
2016/01/28 Javascript
js实现为a标签添加事件的方法(使用闭包循环)
2016/08/02 Javascript
JS中把函数作为另一函数的参数传递方法(总结)
2017/06/28 Javascript
基于Vue制作组织架构树组件
2017/12/06 Javascript
element ui 对话框el-dialog关闭事件详解
2018/02/26 Javascript
React全家桶环境搭建过程详解
2018/05/18 Javascript
用Python中的wxPython实现最基本的浏览器功能
2015/04/14 Python
python3中bytes和string之间的互相转换
2017/02/09 Python
Python编程使用tkinter模块实现计算器软件完整代码示例
2017/11/29 Python
把csv文件转化为数组及数组的切片方法
2018/07/04 Python
python 对key为时间的dict排序方法
2018/10/17 Python
python ---lambda匿名函数介绍
2019/03/13 Python
python3操作注册表的方法(Url protocol)
2020/02/05 Python
解决CSS3 transition-delay 属性默认值0不带单位失效的问题
2020/10/29 HTML / CSS
StubHub澳大利亚:购买或出售您的门票
2019/08/01 全球购物
《尊严》教学反思
2014/02/11 职场文书
2014国庆节国旗下演讲稿(精选版)
2014/09/26 职场文书
十八大宣传标语
2014/10/09 职场文书
销售经理工作失职检讨书
2014/10/24 职场文书
2015年端午节国旗下演讲稿
2015/03/19 职场文书
2016年春季运动会加油稿
2015/07/22 职场文书
Python+Matplotlib+LaTeX玩转数学公式
2022/02/24 Python