【问题标题】:Laravel not making Guzzle HTTP POST request correctlyLaravel 没有正确发出 Guzzle HTTP POST 请求
【发布时间】:2021-06-23 15:30:35
【问题描述】:

我正在研究 megento 集成,并尝试通过使用表单数据发出发布请求来获取管理员访问令牌。我在 Postman 上测试了路线,它工作正常:

但是,当我尝试在 Laravel 中使用 Guzzle Http Client 实现相同的请求时,似乎无法正确发出请求,就好像表单数据帖子正文没有被识别一样,并且它不断向我显示字段值的错误是必须的。这是我的要求:

$client = new \GuzzleHttp\Client();
$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
    'form_params' => [
        'username' => $magento_admin_username,
        'password' => $magento_admin_password
    ], [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json'
    ]
]);

然后这是我不断收到的错误:

更新:我也尝试过这样的请求,它抛出了同样的错误:

$response = $client->post($request['magento_domain'] . '/rest/V1/integration/admin/token', [
    'form_params' => [
        'username' => $magento_admin_username,
        'password' => $magento_admin_password
    ]
]);

我将不胜感激!

【问题讨论】:

    标签: laravel magento2 guzzle


    【解决方案1】:

    发送表单数据正文时“Content-Type: application/json”请求标头不正确。

    只需删除它,Guzzle 会在使用“form_params”时自动添加正确的 Content-Type。只是 JSON 是错误的,因为 body 显然不是 JSON。

    我在生产中成功使用了 JSON 请求:

    $res = $this->client->request('POST', 'https://.../rest/V1/integration/admin/token', [
      'headers' => [
        'Accept' => 'application/json',
        'content-type' => 'application/json'
      ],
      'json' => [
        'username' => config('app.shopUser'),
        'password' => config('app.shopPw')
      ]
    ]);
    

    或者尝试使用“multipart”而不是“form_params”——这应该发送一个multipart/form-data 请求,这就是 Postman 对“form-data”的含义。 “form_params”等价于“x-www-form-urlencoded”。

    【讨论】:

    • 它不能是application/x-www-form-urlencoded,因为当我发出请求是form-url-encode时,响应说:“服务器无法理解Content-Type HTTP header media type application /x-www-form-urlencoded”。所以它必须是表单数据。而我将内容类型设置为 application/json 的原因是因为 Postman 发送的就是这样
    • 无论你设置什么标题,如果你使用“form_params”,正文已经编码为x-www-form:docs.guzzlephp.org/en/stable/request-options.html#form-params“用于发送应用程序/x-www-form-urlencoded POST 请求。” - 我会检查如何发送表单数据请求。
    猜你喜欢
    • 2020-07-14
    • 2020-03-28
    • 2016-07-03
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多