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

调用Steam市场API遇HTTP/1.0 400错误,PHP代码求助

解决Steam社区市场priceoverview接口400 Bad Request错误

问题根源分析

直接浏览器访问正常但PHP调用报错,核心原因通常是两点:

  • 手动拼接URL时参数编码不规范,或html_entity_decode的冗余处理引发格式问题
  • file_get_contents默认请求头缺少浏览器标识,被Steam服务器拦截

解决方案

1. 用http_build_query规范构造URL参数

避免手动拼接&和转义处理,自动完成参数编码,彻底规避格式错误:

// 构造参数数组
$params = [
    'country' => 'FR',
    'currency' => 3,
    'appid' => 730,
    'market_hash_name' => $pts['market_hash_name']
];

// 生成标准格式的URL
$url = 'http://steamcommunity.com/market/priceoverview/?' . http_build_query($params);

2. 模拟浏览器请求头

Steam服务器会验证请求的User-Agent标识,给file_get_contents添加上下文参数模拟浏览器请求:

// 设置Chrome浏览器的请求头
$context = stream_context_create([
    'http' => [
        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n"
    ]
]);

// 携带上下文发起请求
$itemPrice = file_get_contents($url, false, $context);
$itemPriceResponse = json_decode($itemPrice, true);

3. 完整修正代码

$params = [
    'country' => 'FR',
    'currency' => 3,
    'appid' => 730,
    'market_hash_name' => $pts['market_hash_name']
];

$url = 'http://steamcommunity.com/market/priceoverview/?' . http_build_query($params);

$context = stream_context_create([
    'http' => [
        'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36\r\n"
    ]
]);

// 增加错误捕获,方便排查问题
$itemPrice = @file_get_contents($url, false, $context);
if ($itemPrice === false) {
    die('Steam接口请求失败,请检查参数或网络');
}

$itemPriceResponse = json_decode($itemPrice, true);

额外提示

  • 若market_hash_name包含空格、特殊符号等,http_build_query会自动完成URL编码,无需手动处理
  • 可结合error_get_last()函数获取请求失败的具体错误信息,进一步排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:09:24