You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP Curl POST数据未发送问题及Content-Type设置求助

解决PHP Curl POST请求Content-Type及数据格式问题

原代码的两个核心问题

  • 参数构造错误:你把"type: limit"这类字符串放进数组再JSON编码,最终生成的是字符串数组的JSON,而接口需要的是键值对结构的JSON对象,服务器无法正常解析这种格式的数据。
  • 未指定Content-Type请求头:PHP Curl在发送POST数据时,若未明确设置Content-Type,会自动默认使用application/x-www-form-urlencoded,和接口要求的application/json不符,导致数据传输格式不匹配。

修正后的完整代码

// 正确构造关联数组,对应目标JSON的键值结构
$params = [
    "type" => "limit",
    "quantity" => "10",
    "price" => "1",
    "strictValidate" => false
];

// 生成符合接口要求的JSON字符串
$paramsJSON = json_encode($params);

// 请求头中添加Content-Type: application/json,保留原有Accept和Authorization
$headers = [
    "Accept: application/json",
    $auth, // $auth需保持"Authorization: Basic value_for_basic_authentication"格式
    "Content-Type: application/json"
];

$ch = curl_init();

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsJSON);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$res = curl_exec($ch);

// 执行完成后关闭curl资源
curl_close($ch);

关键修正点说明

  1. 参数数组改为关联数组:直接用键=>值的形式定义数组,json_encode后会生成接口需要的{"type":"limit",...}结构,而非原代码的["type: limit",...]无效格式。
  2. 添加Content-Type请求头:在$headers数组里加入"Content-Type: application/json",强制指定请求的Content-Type,覆盖curl的默认值,保证服务器按JSON格式解析POST数据。

内容的提问来源于stack exchange,提问作者PHP-Novice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 13:43:30