我有一个API,并通过Postmen
进行GETEx.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
我在班上添加了这两行
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
$client = new Client();
$res = $client->request('GET','http://site/api/users.count');
dd($ res-> getStatusCode());
我得到了200
DD($水库> 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: []
}
dd($ 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
}
}
如何继续进行调试?
我现在可以接受任何建议。
任何提示/建议/帮助都将非常感谢!
答案 0 :(得分:2)
您可以通过响应标头看到一切正常。状态代码为200,Content-Length
不为0,等等。
回复的正文位于body
的{{1}}属性中,而且是GuzzleHttp\Psr7\Stream
。您可以使用GuzzleHttp\Psr7\Response
方法访问它。
您可以使用getBody()
从响应中读取read($n)
字节,或者通过将n
强制转换为字符串来获取整个响应(通过Stream
)或显式(使用强制转换运算符):
echo
为了将来参考,您可以使用debug mode查看有关整个请求的更多信息:
var_dump((string) $res->getBody()); // explicitly
echo $res->getBody(); // implicitly
答案 1 :(得分:0)
你必须使用$response->getBody();
,你也可以这样做
->getStatusCode();
尝试查看他们的文档,有很多选项,但要使内容使用getBody函数
在您确切的情况下dd($res->getBody());