LoginSignup
27
32

More than 5 years have passed since last update.

guzzle で Http通信する

Posted at
composer require guzzlehttp/guzzle

通信処理

基本的な通信の仕方

use GuzzleHttp\Client;

$client = new Client();
$res = $client->requestAsync($method,$url,$options)->wait();

様々な記法が存在しているが概ね以下の様な形でまとまる。

request()による呼び出しは 内部で requestAsync()->wait() を呼び出す。

get post と言ったメソド名呼び出しは、動的にメソド名を第一引数に据えてrequest を呼び出す。

getAsync postAsync と言ったメソド名呼び出しは、動的にメソド名を第一引数に据えてrequest Asyncを呼び出す。

PSR7 によるリクエスト

PSR7形式でのリクエストオブジェクトが存在する場合には sendメソドが利用できる。

use GuzzleHttp\Psr7\Request;
$request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
$client->send($request,$options);

send と sendAsync の関係は request / requestAsyncの関係とほぼ同じ。

psr7 だけど送信時にoptionを上書き指定することが出来る。

Options

詳しくはこちらを参照
http://docs.guzzlephp.org/en/latest/request-options.html

body / json / form_params / query

文字列、リソースまたはPsr\Http\Message\StreamInterfaceで指定する。

$client->request('PUT', '/put', ['body' => 'some big body string data...']);

json を使用したい場合にはjson キーで配列を渡すほうが楽そう

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

フォームリクエストを行いたい時にはform_params

$client->request('POST', '/post', [
    'form_params' => [
        'foo' => 'bar',
        'baz' => ['hi', 'there!']
    ]
]);

またGETで使用するURLパラメータには query を使用する事

$client->request('GET', '/get', ['query' => ['foo' => 'bar']]);

headers

連想配列で指定する。

$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

http_errors

false にするとエラーをはかなくなる。

デフォルトでは4xx 5xxで例外を投げてくる。

Client オブジェクトの役割

Client 関数にはコンストラクタでオプションを渡す事が可能となっており、
定型的なリクエストのフォーマットを複数送りたい時などに便利。

option の handlerという項目にHandlerStack を追加すると、
リクエスト処理にMiddlewareを追加する事ができるそう。この辺はまた次回暇を見て書きたい。

27
32
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
27
32