使用响应
前面的例子里,我们取到了 $response 变量,或者从Promise得到了响应,Response对象实现了一个PSR-7接口 Psr\Http\Message\ResponseInterface , 包含了很多有用的信息。
你可以获取这个响应的状态码和和原因短语(reason phrase):
1. $code = $response->getStatusCode(); // 200
2. $reason = $response->getReasonPhrase(); // OK
你可以从响应获取头信息(header):
1. // Check if a header exists.
2. if ($response->hasHeader('Content-Length')) {
3. echo "It exists";
4. }
6. // Get a header from the response.
7. echo $response->getHeader('Content-Length');
9. // Get all of the response headers.
10. foreach ($response->getHeaders() as $name => $values) {
11. echo $name . ': ' . implode(', ', $values) . "\r\n";
12. }
使用 getBody 方法可以获取响应的主体部分(body),主体可以当成一个字符串或流对象使用
1. $body = $response->getBody();
2. // Implicitly cast the body to a string and echo it
3. echo $body;
4. // Explicitly cast the body to a string
5. $stringBody = (string) $body;
6. // Read 10 bytes from the body
7. $tenBytes = $body->read(10);
8. // Read the remaining contents of the body as a string
9. $remainingBytes = $body->getContents();
