我有一个API,并通过邮递员对其进行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
我将这两行添加到我的课程顶部
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
$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: []
}
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
}
}
我该如何调试?
您可以通过响应标题看到一切正常。状态代码为200,Content-Length
不为0,等等。
响应的主体位于body
的GuzzleHttp\Psr7\Response
属性中,并且为GuzzleHttp\Psr7\Stream
。您可以使用GuzzleHttp\Psr7\Stream
方法访问它。
您可以使用getBody()
从响应中读取read($n)
字节,或通过隐式地(通过n
)或显式地(使用强制转换运算符)将Stream
强制转换为字符串来获取整个响应:
echo
供将来参考,您可以使用var_dump((string) $res->getBody()); // explicitly
echo $res->getBody(); // implicitly
查看有关整个请求的更多信息:
debug mode
您必须使用$res = $client->request('GET','http://site/api/users.count', ["debug" => true]);
,您也可以执行以下操作$response->getBody();
尝试查看其文档,有很多选择,但是要使用getBody函数获取内容
在您的确切情况下为->getStatusCode();