资讯专栏INFORMATION COLUMN

【PHP类库】Requests - A humble HTTP request library

animabear / 1069人阅读

摘要:相对于等类库来说,它具有简单易用且友好的,且不依赖于。它支持和等方法,基本能满足任何形式的请求。不依赖于任何标准库外的扩展,唯一的要求就是需要的版本。原始的响应数据。标识请求是否成功。

Requests是一个PHP的HTTP类库。相对于cURL等类库来说,它具有简单易用且友好的API,且不依赖于cURL。它支持HEAD、 GET、 POST、 PUT、 DELETE和PATCH等方法,基本能满足任何形式的HTTP请求。

Requests不依赖于任何PHP标准库外的扩展,唯一的要求就是需要PHP5.2+的版本。但是如果PHP的cURL可用,Requests会优先使用它,否则会使用socket。

安装和使用 通过Composer安装
{
    "require": {
        "rmccue/requests": ">=1.0"
    },
    "autoload": {
        "psr-0": {"Requests": "library/"}
    }
}
自动加载

可以使用Composer的加载器:

phpinclude("/path/to/composer/vendor/autoload.php");

也可以使用Requests自带的:

phpinclude("/path/to/library/Requests.php");

Requests::register_autoloader();
各种请求 GET请求
php$response = Requests::get("http://httpbin.org/get");
POST请求
php$response = Requests::post("http://httpbin.org/post");

需要传数据的话,可以使用第三个参数:

php$data = array("key1" => "value1", "key2" => "value2");
$response = Requests::post("http://httpbin.org/post", array(), $data);

如果需要传原始数据的话,第三个参数请传字符串。

其他请求

其他请求方法都大同小异:

php$response = Requests::put("http://httpbin.org/put");

$response = Requests::delete("http://httpbin.org/delete");

$response = Requests::patch("http://httpbin.org/patch", array("If-Match" => "e0023aa4e"));

$response = Requests::head("http://httpbin.org/headers");

需要注意的是equests::patch()方法的第二个参数为必传。

Requests::request()方法

看API文档,你会发现这些方法接受的参数几乎一样:$url$headers$data(只有POST、PUT和PATCH有),$options。事实上它们只是对Requests::request()方法进行了一次封装:

php/**
 * Send a GET request
 */
public static function get($url, $headers = array(), $options = array()) {
    return self::request($url, $headers, null, self::GET, $options);
}

/**
 * Send a HEAD request
 */
public static function head($url, $headers = array(), $options = array()) {
    return self::request($url, $headers, null, self::HEAD, $options);
}

/**
 * Send a DELETE request
 */
public static function delete($url, $headers = array(), $options = array()) {
    return self::request($url, $headers, null, self::DELETE, $options);
}

/**
 * Send a POST request
 */
public static function post($url, $headers = array(), $data = array(), $options = array()) {
    return self::request($url, $headers, $data, self::POST, $options);
}

/**
 * Send a PUT request
 */
public static function put($url, $headers = array(), $data = array(), $options = array()) {
    return self::request($url, $headers, $data, self::PUT, $options);
}

$header允许我们自定义请求头,例如POST方法的话,我们通常需要指定Content-Type,使服务器知道我们正在发送的的数据是什么格式:

php$url = "https://api.github.com/some/endpoint";
$headers = array("Content-Type" => "application/json");
$data = array("some" => "data");
$response = Requests::post($url, $headers, json_encode($data));

$options允许我们对请求进行配置,例如超时时间:

php$options = array(
    "timeout" => 5
);
$response = Requests::get("https://httpbin.org/", array(), $options);
  

更多的选项配置请看:http://requests.ryanmccue.info/api/source-class-Requests.html#_request

Requests里所有的请求方法(HEAD、 GET、 POST、 PUT、 DELETE和PATCH)返回的都是一个Requests_Response对象,这个对象包含了响应的各种信息:

$body:响应体。

$raw:原始的HTTP响应数据。

$headers:响应头。

$status_code:状态码。

$success:标识请求是否成功。

$redirects:请求的重定向次数。

$url:请求的URL。

$history:请求的历史记录。

$cookies:cookie信息。

  

更多Requests_Response的信息请看:http://requests.ryanmccue.info/api/source-class-Requests.html#_request

Session处理

当你需要对同一网站发出多个请求,那么Requests_Session对象可以帮到轻易的设置一些默认参数:

php$url = "https://api.github.com/";
$header = array("X-ContactAuthor" => "rmccue");
$data = array();
$options = array("useragent" => "My-Awesome-App");
$session = new Requests_Session($url, $header, $data, $options);

$response = $session->get("/zen");

Requests_Session的构造函数接受urlheadersdataoptions这4个参数,顺序跟Requests::request()方法一致。同时你也可以通过访问属性的方式去修改options参数:

php// 设置option属性
$session->useragent = "My-Awesome-App";

// 跟上面的作用一致
$session->options["useragent"] = "My-Awesome-App";

更多Requests_Session的信息请看:http://requests.ryanmccue.info/api/source-class-Requests_Session.html

HTTPS请求

Requests会默认帮忙处理HTTPS请求,就跟在浏览器访问HTTPS网站一样:

php$response = Requests::get("https://httpbin.org/");

但是如果你想使用其他的证书或者自签证书,你可以指定证书文件(PEM格式):

php$options = array(
    "verify" => "/path/to/cacert.pem"
);
$response = Requests::get("https://httpbin.org/", array(), $options);

如果你想禁用HTTPS的验证,可以通过设置options"verify" => false

HTTP基本验证

HTTP基本验证功能可以通过optionsauth实现:

php$options = array(
    "auth" => array("user", "password")
);
Requests::get("http://httpbin.org/basic-auth/user/password", array(), $options);
进阶使用 使用代理

代理可以通过optionsproxy实现:

php$options = array(
    "proxy" => "127.0.0.1:3128"
);
Requests::get("http://httpbin.org/ip", array(), $options);

如果代理需要验证:

php$options = array(
    "proxy" => array( "127.0.0.1:3128", "my_username", "my_password" )
);
Requests::get("http://httpbin.org/ip", array(), $options);
钩子

通过Requests的钩子系统,我们可以通过注册自己的钩子去扩展Requests的功能:

php$hooks = new Requests_Hooks();
$hooks->register("requests.after_request", "mycallback");

$request = Requests::get("http://httpbin.org/get", array(), array("hooks" => $hooks));
  

Request提供的钩子请看:http://requests.ryanmccue.info/docs/hooks.html

自定义验证

通过实现Requests_Auth接口,我们可以为请求添加自定义的验证。假设服务器会检查HTTP请求里的Hotdog请求头的值是不是为Yummy。我们先实现我们的验证类:

phpclass MySoftware_Auth_Hotdog implements Requests_Auth {
    protected $password;

    public function __construct($password) {
        $this->password = $password;
    }

    public function register(Requests_Hooks &$hooks) {
        $hooks->register("requests.before_request", array(&$this, "before_request"));
    }

    public function before_request(&$url, &$headers, &$data, &$type, &$options) {
        $headers["Hotdog"] = $this->password;
    }
}

可以看到,类实现了Requests_Auth接口,同时代码实现也用到了钩子。下面我们通过optionsauth去调用我们的自定义验证:

php$options = array(
    "auth" => new MySoftware_Auth_Hotdog("yummy")
);
$response = Requests::get("http://hotdogbin.org/admin", array(), $options);
Why Requests?

文章开始提到了Requests的一些优点,这个官网有个专门的页面进行详细的介绍,同时还提到了Requests跟其他类似类库的对比。通过这个对比,大家对Requests会有进一步的认识,同时也科普下还有哪些HTTP请求相关的类库。
请猛击:http://requests.ryanmccue.info/docs/why-requests.html

参考

http://requests.ryanmccue.info/

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/20964.html

相关文章

  • CodeIgniter框架中抽取部分类库做问题追踪的思路

    摘要:背景由于各种原因,没有接入完整的调用链追踪,。显然,有基本的操作。抽取整个对象的所有对象实例队列中的结果不足框架中不可避免的使用了操作,或者其他业务代码中也使用。这样导致钩子函数无法正常完成他的使用。 背景 由于各种原因,没有接入完整的调用链追踪,(┬_┬)。但是我们自身再通过php的curl调用各端接口时,会请求多次。那么有没有一种方法可以在不植入业务代码的前提下,捕捉到这些curl...

    沈俭 评论0 收藏0
  • 各开源框架使用与设计总结(三)

    摘要:总结了框架与架构的区别。站在框架之外,看框架,看框架的共同特征与功用。由于框架所带来的问题,以性能可扩展问题,相对严重,所以分析性能的改造方向,总结了六大点。包括框架介绍,的使用,以及。 六、各项实践,性能评测 下面进入性能评测,评测我们相对就比较快速一些。直接用ab命令,来测试上面的所提及的一些改进。 以下评测,所有测试页面,均为:http://hjvote.app.ucai.cn/...

    objc94 评论0 收藏0
  • PHP|标准配置之php-fpm.conf

    摘要: ;;;;;;;;;;;;;;;;;;;;; ; FPM Configuration ; ;;;;;;;;;;;;;;;;;;;;; ; All relative paths in this configuration file are relative to PHPs install ; prefix (/usr/local/php). This prefix can be dyn...

    wfc_666 评论0 收藏0
  • PHP 7 新特征

    摘要:本次发布标志着新的重要的系列的开始。经过社区投票,新项目命名为。结果如下结果如下四新特性标量类型声明有两种模式强制默认和严格模式。已废弃的和函数已被移除。在中,如果发生这种情况,会引发错误,并且返回。 最好的语言发布了新的版本,一个划时代的大版本:PHP7。 PHP7修复了大量BUG,新增了功能和语法糖。这些改动涉及到了核心包、GD库、PDO、ZIP、ZLIB等熟悉和不熟悉的核心功能与...

    Channe 评论0 收藏0
  • TP5学习记录(Controller篇)

    摘要:可以在入口文件中定义,然后新建文件夹,达到将应用配置放到该文件的目的,这样方便将配置进行统一管理。动态配置返回数据类型功能同上张三男请求成功 ThinkPHP5 ThinkPHP是一个免费开源的、快速简单的、面向对象的、轻量级PHP开发框架。 为什么选择ThinkPHP5? ThinkPHP5采用了全新的架构思想; 优化了核心是一个颠覆性的版本; 支持composer方式安装; 对...

    leone 评论0 收藏0

发表评论

0条评论

animabear

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<