使用GuzzleHttp消耗API端点时出错

问题描述 投票:0回答:1

我使用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(截断...)

php laravel laravel-5 guzzle
1个回答
0
投票

你看到错误的原因是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
]);
© www.soinside.com 2019 - 2024. All rights reserved.