php使用http请求类库rmccue/requests

说明,这个库可以帮助我们容易的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);

更加轻松愉快呢?
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值