当前位置: 首页 > 工具软件 > Requests(PHP) > 使用案例 >

php使用http请求类库rmccue/requests

桂丰
2023-12-01
说明,这个库可以帮助我们容易的get和post,相比php的curl系列函数接口更加人性化一些。

composer


"rmccue/requests":"1.7.0"


[size=large]普通get和post[/size]
示例代码

//无参get
$response = \Requests::get('https://github.com/timeline.json');
var_dump($response->body);

//带参post
$data = array('key1' => 'value1', 'key2' => 'value2');
$response = \Requests::post('http://httpbin.org/post', array(), $data);
var_dump($response->body);

//带参get
$response = \Requests::get('https://github.com/timeline.json'."?". http_build_query($data) );
var_dump($response->body);




浏览器输出

string(379) "{"message":"Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}"
string(502) "{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Connection": "close",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"Referer": "http://httpbin.org/post",
"User-Agent": "php-requests/1.7"
},
"json": null,
"origin": "115.198.44.160",
"url": "http://httpbin.org/post"
}
"

[size=large]数据流post[/size]
假设我们的post数据不是表单,而是一个整个的数据,比如微信公众号开发post数据是一个json,则可以

$data =[
'button'=>[
[
"type" =>'click',
"name" =>'今日歌曲2',
"key" =>'V1001_TODAY_MUSIC',
],
[
"type" =>'click',
"name" =>'今日歌曲3',
"key" =>'V1001_TODAY_MUSIC3',
],
]
];
$token = Sys::get_wx_gongzhong_token(); // 这里替换一下token
$url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$token;
$headers = array('Content-Type' => 'application/json');
$response = \Requests::post($url, $headers, json_encode($arr, JSON_UNESCAPED_UNICODE ) );
var_dump($response->body);


浏览器返回 微信服务器的通知结果

string(27) "{"errcode":0,"errmsg":"ok"}"


怎么样,是不是感觉比如下代码:

$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
$res = curl_exec($ch);
curl_close($ch);

更加轻松愉快呢?
 类似资料: