Specify raw body of a POST request with Guzzle

2019-08-26 13:02发布

With Guzzle (version 3), I'd like to specify the body of a POST request in "raw" mode. I'm currently trying this:

$guzzleRequest = $client->createRequest(
    'POST',
    $uri,
    null,
    'un=one&deux=two'
);

But it kind of doesn't work. If I dump my $guzzleRequest I can see that postFields->data is empty. Using $guzzleRequest->setBody() afterwards doesn't help.

However if I specify the body as ['un'=>'one', 'deux'=>'two'], it works as expected.

How can I specify the body of the request as 'un=one&deux=two'?

标签: php http guzzle
1条回答
疯言疯语
2楼-- · 2019-08-26 13:36

First I would highly recommend that you upgrade to Guzzle 6 as Guzzle 3 is deprecated and EOL.

It has been a long time since I used Guzzle 3 but I do believe you want the following:

$request = $client->post(
    $uri,
    $header = [],
    $params = [
        'un' => 'one',
        'deux' => 'two',
]);

$response = $request->send();

Guzzle will automatically set the Content-Type header.

More information is available with the Post Request Documentation.

In response to your comment:

$request = $client->post(
    $uri,
    $headers = ['Content-Type' => 'application/x-www-form-urlencoded'],
    EntityBody::fromString($urlencodedstring)
)

For this, reference: EntityBody Source and RequestFactory::create()

查看更多
登录 后发表回答