【问题标题】:Steam API JSON returning bad request 400 only when emptySteam API JSON 仅在为空时返回错误请求 400
【发布时间】:2021-08-02 07:32:30
【问题描述】:

在使用 Steam API 时,我遇到了以下问题:在尝试 to get player achievements 时,它是完美的 - 当它返回结果时,如下所示:

{
   "playerstats":{
      "steamID":"xxxxxxxxxxxxxxxxx",
      "gameName":"Life is Strange™",
      "achievements":[
         {
            "apiname":"AC_1",
            "achieved":1,
            "unlocktime":1620689085
         },
         {
            "apiname":"AC_2",
            "achieved":1,
            "unlocktime":1620677605
         },
         /* ETC, ETC...  */
         {
            "apiname":"AC_60",
            "achieved":0,
            "unlocktime":0
         }
      ],
      "success":true
   }
}

但在某些情况下,产品可能会返回空,因为它没有成就,如下所示:

{
   "playerstats":{
      "error":"Requested app has no stats",
      "success":false
   }
}

然后我收到一个错误 Bad Request 400 for file_get_contents。

我的代码是:

$json_achv = file_get_contents('https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid='. $the_appid .'&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&steamid='. $steam_userid);
$data_jprog = json_decode($json_achv,true);

I have tried this,结果相同(错误请求 400)。 And using curl,json_decode 返回 NULL。

有什么想法吗?

【问题讨论】:

  • 您希望在这里实现什么?一个错误的请求将是一个错误的请求,无论您使用哪个函数来执行它。您链接到的问题是关于错误处理的,但据我所知,您希望这些解决方案能够产生实际的响应数据?
  • 我试图理解为什么它会返回错误的请求,即使 json 存在并且它正在返回结果(如果我直接访问它)。所以我看不出一个错误请求的原因。
  • 似乎是 Steam 支持的问题,而不是 Stack Overflow。 400 状态是否会以任何方式破坏您的申请流程?
  • 我认为这将是file_get_contents 的设计方式;如果你得到一个 4xx 这是一个客户端错误,所以你什么也得不到。例如,这也是 Javascript fetch 的运行方式。虽然您是对的@El_Vanja,错误的请求就是错误的请求,但带有 4xx 的错误响应包含内容是非常常见的(您见过 404 页面吗?)。展望未来,我认为您需要将 null 响应视为没有可返回的内容。
  • 我可以继续删除一些功能(成就进度),但老实说,我不知道我做错了什么,因为即使没有成就也会有 json 响应( “成功:错误”),所以我想它不应该发生。

标签: php json file-get-contents steam-web-api


【解决方案1】:

经过几次测试,我发现 400 Bad Request 与 UTF8 错误有关。无法修改标头,我将file_get_contents 忽略错误

$the_json = 'https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid='. $the_appid.'&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&steamid='. $steam_userid;
$context = stream_context_create(array('http' => array('ignore_errors' => true)));
$json_achv = file_get_contents($the_json, false, $context);
$data_jprog = json_decode($json_achv,true);

现在我可以测试“成功”的真假了。

if ($data_jprog['playerstats']['success'] !== true) {
 echo 'no achievements';
}
else {
 echo 'Total achievements'. count($data_jprog['playerstats']['achievements']);
 // blabla whatever you want to do 
}  

我不知道为什么我之前尝试过但失败了,但它现在可以工作了。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多