首页 > 解决方案 > 调用 API 时解析正文出错

问题描述

我正在开发一个 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
                    ],
                ]);

在邮递员中,我的要求如下 请求头 请求正文

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

标签: phplaravelapiguzzle

解决方案


根据Guzzle 文档

笔记

multipart 不能与 form_params 选项一起使用。您将需要使用其中一个。对 application/x-www-form-urlencoded 请求使用 form_params,对 multipart/form-data 请求使用 multipart。

此选项不能与 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
        ]
    ]
]);

推荐阅读