【问题标题】:Specify raw body of a POST request with Guzzle使用 Guzzle 指定 POST 请求的原始正文
【发布时间】:2016-02-09 13:54:07
【问题描述】:

对于 Guzzle(版本 3),我想以“原始”模式指定 POST 请求的主体。我目前正在尝试这个:

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

但这有点行不通。如果我转储我的$guzzleRequest,我可以看到postFields->data 是空的。之后使用$guzzleRequest->setBody() 没有帮助。

但是,如果我将正文指定为 ['un'=>'one', 'deux'=>'two'],它会按预期工作。

如何将请求正文指定为'un=one&deux=two'

【问题讨论】:

    标签: php http guzzle


    【解决方案1】:

    首先,我强烈建议您升级到 Guzzle 6,因为 Guzzle 3 已弃用且 EOL。

    我已经很久没有使用 Guzzle 3 了,但我相信您想要以下内容:

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

    Guzzle 会自动设置 Content-Type 标头。

    更多信息可通过Post Request Documentation获得。

    回应您的评论:

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

    为此,请参考:EntityBody SourceRequestFactory::create()

    【讨论】:

    • 谢谢肖恩,但这并不能回答我的问题。我想将正文内容作为原始 urlencoded 字符串传递,例如 'un=one&deux=two'
    • 如果我使用new EntityBody('un=one&deux=two'),我会收到Stream must be a resource 错误。如果我使用EntityBody::factory('un=one&deux=two'),我不会收到任何错误,但它不能解决我最初的问题,$request->postFields->data 中没有任何显示
    • 擦掉模糊的眼睛 你可以使用 EntityBody::factory() 或 EntityBody::fromString。
    • 在 Guzzlev3 中(正如您在原始帖子中指出的那样),除非我没有正确阅读源代码,否则 github.com/guzzle/guzzle3/blob/master/src/Guzzle/Http/Message/…github.com/guzzle/guzzle3/blob/master/src/Guzzle/Http/Message/… 中没有“postFields”,您确定您正在使用Guzzle v3?
    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2010-11-06
    • 2015-12-02
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2020-07-14
    • 2014-12-05
    相关资源
    最近更新 更多