读取psr7 http响应中的内容 \Psr\Http\Message\StreamInterface 转化为字符串

* 报错信息

Symfony\Component\Debug\Exception\FatalThrowableError: Cannot use object of type GuzzleHttp\Psr7\Str

Cannot use object of type GuzzleHttp\\Psr7\\Stream as array

GuzzleHttp\\Psr7\\Stream 这种类型的变量$stream 读取里面的内容不能使用 file_get_contents($stream)

或file_get_contents("php://temp"); 应该用 $stream->__toString()

使用php请求URL

https://packagist.org/packages/guzzlehttp/guzzle

网站上的例子

<?php
// ...
$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"id": 1420053, "name": "guzzle", ...}'

// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});
$promise->wait();

* 代码片段

<?php
use \GuzzleHttp\Client;
use Illuminate\Http\Request;
use GuzzleHttp\Psr7\Request as GuzzleRequest;


// ...
$url = "http://172.16.0.245:9200/filebeat-2018.09.12/_search";

$headers = [
    'Content-Type' => 'application/json; charset=UTF-8',
    'User-Agent' => 'guzzlehttp/guzzle'
];

// $o = [];
/*
{"query":{"bool":{"must":[{"match_phrase_prefix":{"request":"\/api\/my\/courses\/free\/"}},{"range":{"@ti\
mestamp":{"gte":"2018-09-12 00:00:00","lte":"2018-09-12 23:59:59","format":"yyyy-MM-dd HH:mm:ss"}}},{"range":{"request_time":{"gte":"1"}}}]}},"sort":[{"r\
equest_time":{"order":"desc"}}],"size":"1000"} ["GET","http://172.16.0.245:9200/filebeat-2018.09.12/_search"
*/
$body = json_encode( $o );

$guzzleRequest = new GuzzleRequest('POST', $url, $headers, $body);
$client = new Client();
$resp = $client->send($guzzleRequest, ['timeout'=>30]);

// use of $resp->body();
// 假设返回的是json 要转化为数组
$res = \GuzzleHttp\json_decode($resp->getBody()->__toString(), true);

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/82864296