我使用Guzzle来使用API,但由于某些原因,我收到此错误:
http_build_query():参数1应该是Array或Object。给出的值不正确。
我不知道我可能做错了什么。这是我的代码:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $jsData
]);
$response = json_decode($call->getBody()->getContents(), true);
编辑
$data = ["name" => "joe doe"];
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $$data
]);
$response = dd($call->getBody()->getContents(), true);
客户端错误:POST http://localhost/send
导致400 BAD REQUEST
响应:{“error”:{“code”:400,“message”:“无法解码JSON对象:无法解码JSON对象”,“u(截断...)
你看到错误的原因是form_params
应该是一个array
但是你通过json_encode
运行数组,它返回一个字符串:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
// ...
'form_params' => $jsonData
您应该简单地将数据作为数组传递,而不是通过json_encode
运行它:
$data = ["name" => "joe doe"];
// ...
$call = $this->client->post(env('URL'), [
"headers" => $headers,
'form_params' => $data
]);