gpt4 book ai didi

PHP - 带有二进制正文数据的 POST 请求 - 适用于 CURL,但不适用于 Laravel

转载 作者:行者123 更新时间:2023-12-05 02:05:32 27 4
gpt4 key购买 nike

我有下面的第 3 方 API,我要将图像发布到。

它们要求 header 的内容类型必须设置为:Content-Type: image/jpeg,并且正文包含实际图像的二进制数据。

下面我在 PHP 中使用 cURL 发出这个请求 - 这很好用:

$url = "examle.org/images";
$pathToFile = "myfile.jpeg";
$auth = "Authorization: Bearer <Token>";

$auth = "Authorization: Bearer " . $this->token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($pathToFile));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: image/jpeg', $auth]);
$result = curl_exec($ch);

上面使用 cURL 的 POST 工作正常:我收到 200 响应成功错误。我想,为了让它更“像 Laravel”,我会使用 Laravel 的 HTTP facade (Guzzle):

$post = Http::withHeaders(['Content-Type' => 'image/jpeg'])
->withToken("<Token>")
->attach('file', file_get_contents($pathToFile), 'myfile.jpeg')
->post($url);

以上没有按预期工作。第 3 方 API 服务返回 400 响应并告诉我它无法读取图像文件。

我做错了什么?

最佳答案

我会尝试 withBody

$post = Http::withBody(file_get_contents($pathToFile), 'image/jpeg')
->withToken("<Token>")
->post($url);

关于PHP - 带有二进制正文数据的 POST 请求 - 适用于 CURL,但不适用于 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63473936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com