Guzzle发布json数据导致400个不良请求

时间:2018-03-05 14:05:09

标签: php json post guzzle

我正在尝试使用guzzle对开放API发布请求。我也发送帖子数据如下。出于某种原因,我收到了400个错误请求

$req = $client->request('POST',$this->base_url.'nutrients?app_id='.$this->app_id.'&app_key='.$this->api_key,[
    'headers' => [
        'Content-Type' => 'application/json'
    ],
    \GuzzleHttp\RequestOptions::JSON => [
        "yield" => $portions,
        "ingredients" => [
            "quantity" => $portions,
            "measureURI" => "\"$f_uri\"",
            "foodURI" => "\"$m_uri\""
        ]
    ]
]);
$response = $client->send($req);
$decoded = json_decode($response->getBody());
dd($decoded);

api文档以curl方式显示方法如下: 卷毛电话:

curl -d @food.json -H "Content-Type: application/json" "https://api.edamam.com/api/food-database/nutrients?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}" 

food.json:

{
    "yield": 1,
    "ingredients": [
        {
            "quantity": 1,
            "measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_unit",
            "foodURI": "http://www.edamam.com/ontologies/edamam.owl#Food_11529"
        }
    ]
}

我正确生成了measureURI和foodURI的链接。

1 个答案:

答案 0 :(得分:0)

您不必在->send()后执行->request(),它已经返回ResponseInterface的实例。

所以只是

$response = $client->request('POST', $this->base_url.'nutrients?app_id='.$this->app_id.'&app_key='.$this->api_key, [
        // ...
    ]
]);
$decoded = json_decode($response->getBody()->getContents());