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

PHP cURL调用登录API时出现Unsupported Media Type错误求助

解决方案:PHP cURL调用登录API解决Unsupported Media Type/400错误

你的问题核心是请求头与参数格式不匹配:一开始用表单格式传参但接口不接受(返回UnsupportedMediaType),后来添加JSON请求头却未将参数转为正确的JSON格式(导致400错误)。以下分两种常见场景给出可直接运行的代码示例:

场景1:接口要求JSON格式参数

如果API文档明确要求用application/json提交参数,必须满足两个关键点:

  • 请求头设置Content-Type: application/json
  • POST参数必须是JSON字符串(不能直接传递PHP数组)

示例代码:

<?php
$apiUrl = "你的登录API地址";
$loginParams = [
    'Username' => '你的用户名',
    'Password' => '你的密码',
    'Appkey' => '你的AppKey'
];

$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
// 设置JSON类型请求头
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Accept: application/json' // 明确告知接口你接受JSON格式响应
]);
// 将PHP数组转为JSON字符串作为请求体
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($loginParams));

$response = curl_exec($curl);
$httpStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpStatusCode === 200) {
    $result = json_decode($response, true);
    // 根据接口实际返回字段提取Token ID,这里假设字段是TokenID
    $tokenId = $result['TokenID'] ?? null;
    if ($tokenId) {
        echo "Token获取成功:" . $tokenId;
    } else {
        echo "响应中未找到Token ID字段";
    }
} else {
    echo "请求失败,状态码:{$httpStatusCode},响应内容:{$response}";
}

curl_close($curl);
?>

场景2:接口要求表单格式参数

如果API实际接受application/x-www-form-urlencoded格式(即普通表单提交),需确保请求头与参数格式匹配:

  • 可显式设置Content-Type: application/x-www-form-urlencoded请求头
  • 直接传递PHP数组即可(cURL会自动编码并设置正确的请求头)

示例代码:

<?php
$apiUrl = "你的登录API地址";
$loginParams = [
    'Username' => '你的用户名',
    'Password' => '你的密码',
    'Appkey' => '你的AppKey'
];

$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
// 显式设置表单类型请求头(可选,cURL传数组时会自动设置)
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded',
    'Accept: application/json'
]);
// 直接传递PHP数组,cURL会自动编码为表单格式
curl_setopt($curl, CURLOPT_POSTFIELDS, $loginParams);

$response = curl_exec($curl);
$httpStatusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpStatusCode === 200) {
    $result = json_decode($response, true);
    $tokenId = $result['TokenID'] ?? null;
    if ($tokenId) {
        echo "Token获取成功:" . $tokenId;
    } else {
        echo "响应中未找到Token ID字段";
    }
} else {
    echo "请求失败,状态码:{$httpStatusCode},响应内容:{$response}";
}

curl_close($curl);
?>

调试技巧(排查问题用)

如果仍报错,可开启cURL调试模式查看原始请求内容,确认是否符合接口要求:

// 在执行curl_exec前添加以下代码
curl_setopt($curl, CURLOPT_VERBOSE, true);
$debugLog = fopen('php://temp', 'w+');
curl_setopt($curl, CURLOPT_STDERR, $debugLog);

// 执行请求后读取调试日志
rewind($debugLog);
$logContent = stream_get_contents($debugLog);
echo "请求调试日志:<pre>{$logContent}</pre>";

内容的提问来源于stack exchange,提问作者Ospite

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 07:22:35