【问题标题】:Laravel 7 HTTP Client - Unable to send POST request with `body`Laravel 7 HTTP 客户端 - 无法使用“body”发送 POST 请求
【发布时间】:2020-08-16 10:18:51
【问题描述】:

使用 Laravel 7.6 和它的内置 HTTP 客户端。

我正在尝试向我的其他域发送一个带有 body 的原始 JSON 格式的简单 POST 请求,但没有成功:

$response = Http::post('https://example.com', [
    'body' => '{ test: 1 }'
]);

我收到 400 Bad Request - Client error - 因为我的服务器要求 body 是强制性的。

我在这里错过了什么?

【问题讨论】:

    标签: laravel http request guzzle laravel-7


    【解决方案1】:
    $response = Http:post('http://example.com/', [
       'foo' =>   'bar'
    ]);
    

    或者这个

    $response = Http::withHeaders([
     'User-Agent' => 'Some Agent',
    ])->asForm()->post('http://www.example.com/', [
      'foo' => 'bar',
    ]);
    

    【讨论】:

      【解决方案2】:

      试试这个,在我的情况下应该可以。

      $response = Http::withHeaders(['Content-Type' => 'application/json'])
          ->send('POST', 'https://example.com', [
              'body' => '{ test: 1 }'
          ])->json();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-14
        • 2022-07-14
        • 2022-01-15
        • 2015-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-20
        相关资源
        最近更新 更多