17

我正在尝试构建一个端点,将传递给它的数据转发到使用 Slim PHP 框架的 API,但我无法从 Guzzle 请求中获取响应。

$app->map( '/api_call/:method', function( $method ) use( $app ){
    $client = new GuzzleHttp\Client([
        'base_url' => $app->config( 'api_base_url' ),
        'defaults' => [
            'query'   => [ 'access_token' => 'foo' ],
        ]
    ]);

    $request = $client->createRequest( $app->request->getMethod(), $method, [
        'query' => $app->request->params()
    ]);

    var_dump( $client->send( $request )->getBody() );

})->via( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE' )->conditions( [ 'route' => '.+?' ] );`

然后这给了我...

object(GuzzleHttp\Stream\Stream)[59]
  private 'stream' => resource(72, stream)
  private 'size' => null
  private 'seekable' => boolean true
  private 'readable' => boolean true
  private 'writable' => boolean true
  private 'meta' => 
    array (size=6)
     'wrapper_type' => string 'PHP' (length=3)
      'stream_type' => string 'TEMP' (length=4)
      'mode' => string 'w+b' (length=3)
      'unread_bytes' => int 0
      'seekable' => boolean true
      'uri' => string 'php://temp' (length=10)

...而不是我期待的“酷”的回应。

如果我只是 var_dump$client->sendRequest( $request )我得到 200 OK,并且 url 是我所期望的,http://localhost:8000/test?access_token=foo.

我有另一个请求,但只使用$client->post(...)它并且它工作正常而没有给我流的东西。

我尝试使用底部的示例(http://guzzle.readthedocs.org/en/latest/http-client/response.html)读取流,但它告诉我feof不存在。

有人知道我在这里遗漏了什么或做错了什么吗?

4

4 回答 4

27

可能;

$response = $client->send($request)->getBody()->getContents();
$response = $client->send($request)->getBody()->read(1024*100000);

这也可以作为速记;

$response = ''. $client->send($request)->getBody();
$response = (string) $client->send($request)->getBody();

//__toString()最后一个例子见方法:http: //php.net/manual/en/language.oop5.magic.php#object.tostring

于 2015-02-12T15:43:57.723 回答
13

我遇到了同样的问题,问题是,如果你 getBody 它是一个流,这意味着它有一个指针,当你在它上面执行 getContents 时,它会将指针留在文件末尾,这意味着如果你想得到身体多次你需要寻找指针回到0。

$html1 = $this->response->getBody()->getContents();
$this->response->getBody()->seek(0);
$html2 = $this->response->getBody()->getContents();
$this->response->getBody()->seek(0);

这应该工作:)

@mrW 我希望这对你有帮助

于 2015-09-10T08:56:42.180 回答
9

您正在 var_dumping 的主体是 Guzzle 流对象。可以将此对象视为字符串或根据需要从中读取。Guzzle Stream 的文档在这里

于 2014-04-03T16:01:34.433 回答
3

Just had a strange situation. Note that you can get body content only once!

I have expected to get same content every time I call getContents().

$html1 = $this->response->getBody()->getContents();
$html2 = $this->response->getBody()->getContents();

$same = ($html1 == $html2);

strlen($html1); //x
strlen($html2); //0

But they are not! I have missed information that Guzzle response is stream so with first getContents() we read all contents and nothing is left for second call.

于 2015-04-26T15:17:33.460 回答