php Guzzlehttp - 如何从 Guzzle 6 获取响应正文?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30549226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:52:33  来源:igfitidea点击:

Guzzlehttp - How get the body of a response from Guzzle 6?

phpresponseguzzleguzzle6

提问by Greg

I'm trying to write a wrapper around an api my company is developing. It's restful, and using Postman I can send a post request to an endpoint like http://subdomain.dev.myapi.com/api/v1/auth/with a username and password as POST data and I am given back a token. All works as expected. Now, when I try and do the same from PHP I get back a GuzzleHttp\Psr7\Responseobject, but can't seem to find the token anywhere inside it as I did with the Postman request.

我正在尝试为我公司正在开发的 api 编写一个包装器。它很安静,使用 Postman 我可以向端点发送一个 post 请求,比如http://subdomain.dev.myapi.com/api/v1/auth/使用用户名和密码作为 POST 数据,然后我得到一个令牌。一切都按预期工作。现在,当我尝试从 PHP 执行相同操作时,我会返回一个GuzzleHttp\Psr7\Response对象,但似乎无法像处理 Postman 请求那样在其中的任何地方找到令牌。

The relevant code looks like:

相关代码如下所示:

$client = new Client(['base_uri' => 'http://companysub.dev.myapi.com/']);
$response = $client->post('api/v1/auth/', [
    'form_params' => [
        'username' => $user,
        'password' => $password
    ]
]);

var_dump($response); //or $resonse->getBody(), etc...

The output of the code above looks something like (warning, incoming wall of text):

上面代码的输出看起来像(警告,传入的文本墙):

object(guzzlehttp\psr7\response)#36 (6) {
  ["reasonphrase":"guzzlehttp\psr7\response":private]=>
  string(2) "ok"
  ["statuscode":"guzzlehttp\psr7\response":private]=>
  int(200)
  ["headers":"guzzlehttp\psr7\response":private]=>
  array(9) {
    ["connection"]=>
    array(1) {
      [0]=>
      string(10) "keep-alive"
    }
    ["server"]=>
    array(1) {
      [0]=>
      string(15) "gunicorn/19.3.0"
    }
    ["date"]=>
    array(1) {
      [0]=>
      string(29) "sat, 30 may 2015 17:22:41 gmt"
    }
    ["transfer-encoding"]=>
    array(1) {
      [0]=>
      string(7) "chunked"
    }
    ["content-type"]=>
    array(1) {
      [0]=>
      string(16) "application/json"
    }
    ["allow"]=>
    array(1) {
      [0]=>
      string(13) "post, options"
    }
    ["x-frame-options"]=>
    array(1) {
      [0]=>
      string(10) "sameorigin"
    }
    ["vary"]=>
    array(1) {
      [0]=>
      string(12) "cookie, host"
    }
    ["via"]=>
    array(1) {
      [0]=>
      string(9) "1.1 vegur"
    }
  }
  ["headerlines":"guzzlehttp\psr7\response":private]=>
  array(9) {
    ["connection"]=>
    array(1) {
      [0]=>
      string(10) "keep-alive"
    }
    ["server"]=>
    array(1) {
      [0]=>
      string(15) "gunicorn/19.3.0"
    }
    ["date"]=>
    array(1) {
      [0]=>
      string(29) "sat, 30 may 2015 17:22:41 gmt"
    }
    ["transfer-encoding"]=>
    array(1) {
      [0]=>
      string(7) "chunked"
    }
    ["content-type"]=>
    array(1) {
      [0]=>
      string(16) "application/json"
    }
    ["allow"]=>
    array(1) {
      [0]=>
      string(13) "post, options"
    }
    ["x-frame-options"]=>
    array(1) {
      [0]=>
      string(10) "sameorigin"
    }
    ["vary"]=>
    array(1) {
      [0]=>
      string(12) "cookie, host"
    }
    ["via"]=>
    array(1) {
      [0]=>
      string(9) "1.1 vegur"
    }
  }
  ["protocol":"guzzlehttp\psr7\response":private]=>
  string(3) "1.1"
  ["stream":"guzzlehttp\psr7\response":private]=>
  object(guzzlehttp\psr7\stream)#27 (7) {
    ["stream":"guzzlehttp\psr7\stream":private]=>
    resource(40) of type (stream)
    ["size":"guzzlehttp\psr7\stream":private]=>
    null
    ["seekable":"guzzlehttp\psr7\stream":private]=>
    bool(true)
    ["readable":"guzzlehttp\psr7\stream":private]=>
    bool(true)
    ["writable":"guzzlehttp\psr7\stream":private]=>
    bool(true)
    ["uri":"guzzlehttp\psr7\stream":private]=>
    string(10) "php://temp"
    ["custommetadata":"guzzlehttp\psr7\stream":private]=>
    array(0) {
    }
  }
}

The output from Postman was something like:

Postman 的输出类似于:

{
    "data" : {
        "token" "fasdfasf-asfasdfasdf-sfasfasf"
    }
}

Clearly I'm missing something about working with the response objects in Guzzle. The Guzzle response indicates a 200 status code on the request, so I'm not sure exactly what I need to do to retrieve the returned data.

很明显,我缺少关于在 Guzzle 中使用响应对象的一些内容。Guzzle 响应在请求中指示 200 状态代码,所以我不确定我需要做什么来检索返回的数据。

回答by Federkun

Guzzle implements PSR-7. That means that it will by default store the body of a message in a Streamthat uses PHP temp streams. To retrieve all the data, you can use casting operator:

Guzzle 实现了PSR-7。这意味着默认情况下它会将消息正文存储在使用 PHP 临时流的Stream中。要检索所有数据,您可以使用强制转换运算符:

$contents = (string) $response->getBody();

You can also do it with

你也可以这样做

$contents = $response->getBody()->getContents();

The difference between the two approaches is that getContentsreturns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with rewindor seek.

两种方法之间的区别在于getContents返回剩余的内容,因此除非您使用rewind或查找流的位置,否则第二次调用将不返回任何内容seek

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents

Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.

相反,使用 PHP 的字符串转换操作,它将从流中读取从头到尾的所有数据。

$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents

Documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

文档:http: //docs.guzzlephp.org/en/latest/psr7.html#responses

回答by Maksim Ivanov

If expecting JSON back, the simplest way to get it:

如果期望返回 JSON,获取它的最简单方法是:

$data = json_decode($response->getBody()); // returns an object

// OR

$data = json_decode($response->getBody(), true); // returns an array

json_decode()will automatically cast the body to string, so there is no need to call getContents().

json_decode()会自动投身到string,所以没有必要调用getContents()