【问题标题】:Guzzle post json data causing 400 bad requestGuzzle post json 数据导致 400 错误请求
【发布时间】:2018-08-13 05:06:36
【问题描述】:

我正在尝试使用 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 链接生成正确。

【问题讨论】:

  • $this->base_url 是什么?是 $this->base_url = "h ttp s: // api.edamam.com/api/food-database/"; ?
  • genesis - 我们不使用 "var" 在 PHP 中定义变量。
  • 是的,刚刚改了。仍然没有什么不同。

标签: php json post guzzle


【解决方案1】:

你不需要在->request()之后做->send(),它已经返回了一个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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2014-09-22
    • 2018-12-06
    相关资源
    最近更新 更多