使用GuzzleHttp消耗API端点的错误

时间:2018-09-03 10:47:04

标签: php laravel laravel-5 guzzle

我正在使用Guzzle使用API​​,但由于某些原因,出现此错误:

  

http_build_query():参数1应该是数组或对象。输入的值不正确。

我不知道我在做什么错。这是我的代码:

$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响应:{“错误”:{“代码”:400,“消息”:“无法解码JSON对象:无法解码JSON对象“,” u(被截断...)

1 个答案:

答案 0 :(得分: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
]);