1. 程式人生 > >Http Requests for PHP

Http Requests for PHP

一、Requests for PHP

官網:http://requests.ryanmccue.info
官方介紹:
Requests is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.
Requests是一個謙虛的HTTP請求類庫,它簡化你與其他網站的互動並把你的一些煩惱帶走。
如何使用:
1、下載:https://github.com/rmccue/Requests/archive/v1.6.0.zip 
2、解壓縮,得到如下檔案

 

把library目錄重名稱為requests,然後拷貝到程式的類庫資料夾

3、引用類庫檔案

require_once ('requests/Requests.php');
4、讓程式自動引用相關內部類庫(一定要執行這行程式碼)


Requests::register_autoloader();
5、開始使用GET或POST請求獲取遠端資料

$response = Requests::get('https://github.com/timeline.json');
var_dump($response);

常用方法說明:
1、使用GET傳送請求獲取遠端資料 Requests::get($url, $headers = array(), $options = array());
這裡有3個引數可以使用
第1個引數:$url 為需要獲取遠端資料的url連結,例如:


$response = Requests::get('https://github.com/timeline.json');
第2個引數:$headers = array() 為附加的頭部請求

array('Accept' => 'application/json')

 

第3個引數:$options = array() 為配置引數

`timeout`: 設定響應超時時間
(integer, seconds, default: 10)
`useragent`: 設定傳送到伺服器的使用者代理
(string, default: php-requests/$version)
`follow_redirects`: 是否允許3XX重定向
(boolean, default: true)
`redirects`: How many times should we redirect before erroring?
(integer, default: 10)
`blocking`: Should we block processing on this request?
(boolean, default: true)
`filename`: File to stream the body to instead.
(string|boolean, default: false)
`auth`: Authentication handler or array of user/password details to use for Basic authentication
(Requests_Auth|array|boolean, default: false)
`proxy`: Proxy details to use for proxy by-passing and authentication
(Requests_Proxy|array|boolean, default: false)
`idn`: Enable IDN parsing
(boolean, default: true)
`transport`: Custom transport. Either a class name, or a transport object. Defaults to the first working transport from
{@see getTransport()}
(string|Requests_Transport, default: {@see getTransport()})
`hooks`: Hooks handler.
(Requests_Hooker, default: new Requests_Hooks())
`verify`: Should we verify SSL certificates? Allows passing in a custom
certificate file as a string. (Using true uses the system-wide root
certificate store instead, but this may have different behaviour
across transports.)
(string|boolean, default: library/Requests/Transport/cacert.pem)
`verifyname`: Should we verify the common name in the SSL certificate?
(boolean: default, true)

2、使用POST傳送請求獲取遠端資料 Requests::post($url, $headers = array(), $data = array(), $options = array());
這裡有4個引數可以使用,多了一個請求資料(相當於表單提交的資料),其實get也有這個資料,get請求直接附加在url上了

第1個引數:$url 同get的第一個引數
第2個引數:$headers = array() 同get的第2個引數
第4個引數:$options = array() 同get的第3個引數
第3個引數:$data = array() 為表單提交的資料