guzzle 简单使用记录

用 guzzle 发送一个包含指定请求头,请求体的 post 请求,并获取指定内容:

 1 <?php
 2 
 3 include_once "guzzle.phar";
 4 use GuzzleHttp\Client;
 5 use GuzzleHttp\Psr7\Request;
 6 use Psr\Http\Message\ResponseInterface;
 7 
 8 $base_uri = "127.0.0.1:8082/";
 9 
10 $method = "POST";//请求方式
11 
12 $data = array(
13     "xxxx" => "xxx",
14 );
15 
16 $headers = array(//添加请求头
17     "Authorization" => " Basic " . base64_encode("testing:dhskln")
18 );
19 
20 $options = array(//请求体
21     "headers" => $headers,
22     "body" => json_encode($data),
23 );
24 
25 $send_request = new Client(["base_uri" => $base_uri]);
26 
27 $api = "host/test";
28 
29 $result = $send_request->request($method, $api, $options);
30 
31 print_r($result);
32 
33 $code = $result->getStatusCode(); // 获取响应码
34 echo $code;
35 $body = $result->getBody();//获取返回体
36 echo $body;

 

遇到的问题1:

虽然代码中加了 use GuzzleHttp\Client;,但是没有引用 guzzle.pahr 文件

解决方法:在 use 前加上 include_once "guzzle.phar"; 即可

遇到的问题2:

body 没有使用 json 编码

解决方法:

 

 

详细的 guzzle 使用文档见:https://guzzle-cn.readthedocs.io/zh_CN/latest/quickstart.html

 

posted @ 2018-09-30 20:00  geloutingyu  阅读(742)  评论(0编辑  收藏  举报