调用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
相关产品推荐
相关产品推荐

