如何获取CS2用户库存为JSON对象?请求遇403错误需配置API密钥吗?
问题分析与解决方案
为什么会出现403错误?
你遇到的403错误是Steam反爬机制拦截了请求导致的——浏览器访问时会自动携带User-Agent这类标识请求头,而你的代码里没有添加这些信息,服务器会判定请求来源不合法,从而返回403。
是否需要API密钥?
- 针对公开库存:直接调用
steamcommunity.com的库存接口不需要API密钥,但必须模拟浏览器的请求头。 - 针对私有库存或需要长期稳定、高频率的访问:建议使用Steam Web API的
GetInventory接口,这时候需要配置Steam API密钥(可在Steam开发者平台申请)。
修复代码示例
给HttpURLConnection添加必要的请求头,模拟浏览器请求:
try { URL url = new URL("https://steamcommunity.com/profiles/" + steamID + "/inventory/json/730/2"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 添加模拟浏览器的请求头 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"); conn.setRequestProperty("Accept-Language", "en-US,en;q=0.9"); int statusCode = conn.getResponseCode(); if(statusCode != HttpURLConnection.HTTP_OK) { throw new IOException("Received non-OK response from server: " + statusCode); } // 后续读取响应内容的逻辑 } catch (IOException e) { e.printStackTrace(); }
额外注意事项
- 如果添加请求头后仍出现403,可尝试从登录Steam的浏览器中复制
Cookie添加到请求头,但这种方式不适合长期使用,因为Cookie会过期。 - 若需要长期稳定的库存访问,优先使用Steam Web API,接口格式示例:
https://api.steampowered.com/IEconItems_730/GetPlayerItems/v1/?key=YOUR_API_KEY&steamid=STEAM_ID,该方式需API密钥,数据获取更可靠。
内容的提问来源于stack exchange,提问作者Yash Salunke
相关产品推荐
相关产品推荐

