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

PHP调用接口出现HTTP/1.1 415错误,求排查原因及解决建议

错误原因分析

HTTP 415 "Unsupported Media Type" 错误的核心原因是:你的PHP请求没有携带服务器接口要求的Content-Type请求头,或者发送的请求数据格式不符合接口预期。Postman能正常调用,说明Postman自动帮你设置了正确的请求头和数据格式,而你的PHP代码遗漏了这些关键配置。

解决建议

1. 明确接口要求的媒体类型

先确认Postman里调用该接口时使用的Content-Type(通常在Headers标签里),常见的类型包括:

  • application/json(JSON格式数据)
  • application/x-www-form-urlencoded(表单键值对)
  • multipart/form-data(文件上传场景)

2. 修正PHP请求的上下文配置

使用file_get_contents发送POST请求时,必须通过stream_context_create创建包含请求头和请求体的上下文。以下是两种常见场景的示例:

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

// 构造要发送的JSON数据
$data = [
    'title' => '测试博客',
    'content' => '博客内容示例'
];
$jsonData = json_encode($data);

// 创建请求上下文
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($jsonData) // 可选但推荐添加,帮助服务器识别数据长度
        ],
        'content' => $jsonData
    ]
]);

// 发送请求并处理响应
$response = file_get_contents('http://localhost:8080/project_war_exploded/admin/blog', false, $context);
if ($response === false) {
    var_dump(error_get_last());
} else {
    echo $response;
}

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

// 构造表单数据,自动编码为键值对格式
$data = http_build_query([
    'title' => '测试博客',
    'content' => '博客内容示例'
]);

// 创建请求上下文
$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    ]
]);

// 发送请求并处理响应
$response = file_get_contents('http://localhost:8080/project_war_exploded/admin/blog', false, $context);
if ($response === false) {
    var_dump(error_get_last());
} else {
    echo $response;
}

3. 额外排查点

  • 检查Postman中是否还有其他自定义请求头(比如Authorization令牌),如果有,需要在PHP的header数组中一并添加。
  • 用json_last_error()检查json_encode是否成功,避免发送无效的JSON数据。
  • 确保请求数据的编码和服务器一致(通常为UTF-8)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:15:38