Specify raw body of a POST request with Guzzle

放肆的年华 提交于 2019-12-12 04:04:55

问题


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'?


回答1:


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()



来源:https://stackoverflow.com/questions/35293841/specify-raw-body-of-a-post-request-with-guzzle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!