使用Guzzle使用JSON发送POST请求

Kir*_*ira 2 php laravel guzzle

$client = new Client();
$url = 'api-url';

$request = $client->post($url, [
    'headers' => ['Content-Type' => 'application/json'],
    'json' => ['token' => 'foo']
]);

return $request;
Run Code Online (Sandbox Code Playgroud)

然后我回来502 Bad Gateway并将资源解释为文档,但使用MIME类型application/json进行传输

我需要用一些json发出POST请求.我怎么能在Laravel的Guzzle中做到这一点?

Mor*_*abi 6

试试看

$response = $client->post('http://api.example.com', [
    'json' => [
       'key' => 'value'
     ]
]);

dd($response->getBody()->getContents());
Run Code Online (Sandbox Code Playgroud)

  • 它应该是$ request in dd()而不是$ result.并且缺少方括号.$ request = $ client-> post('http://api.example.com',['json'=> ['key'=>'value']]); DD($请求 - > getBody() - > getContents()); (2认同)