LoginSignup
4
4

More than 3 years have passed since last update.

Guzzleでリクエスト、レスポンスを取得する方法

Last updated at Posted at 2020-07-12

公式のドキュメントより一部抜粋。完全に自分のメモ。
ログを残すときとかに便利。

以下のようなありがちなリクエストを想定。

$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);

リクエスト・レスポンスボディを取得する方法

getbody()を使う。ボディがStringでキャストされる。
このとき、リクエストを取得するには#request->getbody()してあげる。

use GuzzleHttp\Middleware;

// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
    echo $request->getHeaderLine('Content-Type');
    // application/json
    echo $request->getBody();
    // {"foo":"bar"}
});

レスポンスを取得するには$response->getbody()してあげる。ミドルウェアを使わないといけないっぽい。
Guzzleのミドルウェアについては、この記事が詳しいです。

$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();

ちなみにread()を使うと指定したbyteだけ取得してくれるらしいです。重いデータとか用いるときには指定したい。

ステータスコード・フレーズを取得する方法

200 OKとかそういうのをそれぞれ取得してくれます。

$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

公式ドキュメント

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4