我有一个API,并通过Postman进行GET访问:
Ex.http://site/api/users.count
我得到了
{
"status": 200,
"message": "Success",
"data": {
"count": 8
}
}
我尝试使用Guzzle:
composer require guzzlehttp/guzzle
Using version ^6.3 for guzzlehttp/guzzle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing guzzlehttp/promises (v1.3.1)
Downloading: 100%
- Installing psr/http-message (1.0.1)
Loading from cache
- Installing guzzlehttp/psr7 (1.4.2)
Loading from cache
- Installing guzzlehttp/guzzle (6.3.0)
Downloading: 100%
Writing lock file
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader
<小时 />包括它
我在课程顶部添加这 2 行
use GuzzleHttpExceptionGuzzleException;
use GuzzleHttpClient;
<小时 />使用它
$client = new Client();
$res = $client->request('GET','http://site/api/users.count');
<小时 />结果
dd($res->getStatusCode());
我得到了200
dd($res->getBody());
Stream {#662 ▼
-stream: stream resource @272 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
日($res);
我得到了
Response {#664 ▼
-reasonPhrase: "OK"
-statusCode: 200
-headers: array:4 [▼
"Connection" => array:1 [▼
0 => "Keep-Alive"
]
"Content-Length" => array:1 [▼
0 => "61"
]
"Content-Type" => array:1 [▼
0 => "application/json; charset=utf-8"
]
"Date" => array:1 [▼
0 => "Wed, 18 Oct 2017 18:01:50 GMT"
]
]
-headerNames: array:4 [▼
"connection" => "Connection"
"content-length" => "Content-Length"
"content-type" => "Content-Type"
"date" => "Date"
]
-protocol: "1.1"
-stream: Stream {#662 ▼
-stream: stream resource @272 ▼
wrapper_type: "PHP"
stream_type: "TEMP"
mode: "w+b"
unread_bytes: 0
seekable: true
uri: "php://temp"
options: []
}
-size: null
-seekable: true
-readable: true
-writable: true
-uri: "php://temp"
-customMetadata: []
}
}
<小时 />预期成果
我希望得到这样的类似结果:
{
"status": 200,
"message": "Success",
"data": {
"count": 8
}
}
我该如何调试?
您可以通过响应标头看到一切正常。 状态代码为 200,Content-Length
不是 0,依此类推。
响应的主体位于GuzzleHttpPsr7Response
的body
属性中,它是一个GuzzleHttpPsr7Stream
。您可以使用getBody()
方法访问它。
您可以使用 read($n)
从响应中读取 n
个字节,或者通过将Stream
转换为字符串来获取整个响应,无论是隐式(通过 echo
)还是显式(使用 cast 运算符):
var_dump((string) $res->getBody()); // explicitly
echo $res->getBody(); // implicitly
为了将来参考,您可以使用调试模式查看有关整个请求的详细信息:
$res = $client->request('GET','http://site/api/users.count', ["debug" => true]);
你必须使用$response->getBody();
你也可以做一些事情,比如 ->getStatusCode();
尝试查看他们的文档,有很多选择,但要获取内容,请使用getBody函数
在您的确切情况下dd($res->getBody());