gpt4 book ai didi

PHP 通过 curl 发送 POST 请求

转载 作者:可可西里 更新时间:2023-11-01 13:50:21 24 4
gpt4 key购买 nike

我需要使用 curl 向外部 http API 发出 POST 请求。当我使用 curl 命令行调用 API 时,它返回正确的数据。但是,从 php 脚本调用它时,我很难获得正确的数据。

当我从终端使用 curl 命令时,我得到了正确的数据:

curl -i -H "Accept: application/json"-X POST -d "type_category_id=4"http://example.com/api/

我在 php 中的 curl_setopts() 中的 CURLOPT_POSTFIELDS 的正确格式是什么?

我尝试了以下(但失败了):

<?php
$data = "type_category_id=4";

$ch = curl_init('http://example.com/api/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);

$result = curl_exec($ch);
?>

最佳答案

让它成为 Accept: application/json 而不是 Content-Type: application/json

您已经在命令行中完成了该操作,但没有在 php 脚本中完成。

关于PHP 通过 curl 发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319477/

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