【问题标题】:There was an error parsing the body when calling an API调用 API 时解析正文出错
【发布时间】:2020-11-23 02:41:15
【问题描述】:

我正在开发一个 OCR 项目,我正在尝试使用 vidado API。当我通过 posman 发送发布请求时,它给了我正确的响应,但是当我从 php 调用 API 时,它给了我以下错误

Client error: `POST https://api.vidado.ai/read/text` resulted in a `400 Bad Request` response: {"detail":"There was an error parsing the body"}

我的代码是

$client = new \GuzzleHttp\Client();
                $url   = "https://api.vidado.ai/read/text";

                $requestAPI = $client->post( $url, [
                    'headers' => [
                        'Accept' => 'application/json',
                        'Authorization' => 'my apikey',
                        'Content-Type' => 'multipart/form-data'
                    ],
                    'form_params' => [
                        'autoscale' => 'true',
                        'image'=> $img
                    ],
                ]);

在邮递员中,我的要求如下

有人注意到实际的错误吗?所以请给我一个方法来做到这一点。 谢谢。

【问题讨论】:

  • 你在 $img 里面放了什么?
  • @krylov123 图像对象
  • 检查我的更新答案

标签: php laravel api guzzle


【解决方案1】:

根据Guzzle documentation

注意

multipart 不能与 form_params 选项一起使用。您将需要 使用其中一种。使用 form_params application/x-www-form-urlencoded 请求,以及多部分 多部分/表单数据请求。

此选项不能与 body、form_params 或 json 一起使用

因此您不能将 form_params 与 multipart/form-data 一起使用,您必须以这种方式使用 multipart 方法:

$client = new \GuzzleHttp\Client();
$url   = "https://api.vidado.ai/read/text";

$requestAPI = $client->request('POST', $url, [
    'headers' => [
        'Accept' => 'application/json',
        'Authorization' => 'my apikey',
        'Content-Type' => 'multipart/form-data'
    ],
    'multipart' => [
        [
            'name'     => 'image',
            'contents' => fopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.jpg'
        ],
        [
            'name' => 'autoscale',
            'contents'=> true
        ]
    ]
]);

【讨论】:

  • 感谢您回答我,但我仍然遇到同样的错误。这是我的文件路径和文件名“/home/madusanka/OX/ocr/storage/app/public/uploaded_images/3/selections/1.png”、“1.png”
  • 它在从标题部分删除 Content-Type 键时起作用。我可以从[stackoverflow.com/questions/47550801/…找到原因。谢谢你的回答。
猜你喜欢
  • 2016-01-30
  • 1970-01-01
  • 2015-07-06
  • 2018-09-24
  • 2018-10-21
  • 1970-01-01
  • 2014-10-20
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多