【问题标题】:PHP file_get_contents returns with a 400 ErrorPHP file_get_contents 返回 400 错误
【发布时间】:2017-09-30 16:38:35
【问题描述】:

我的问题很简单,但我终其一生都无法弄清楚哪里出了问题。我用另一个 API 做了类似的事情,但这只是讨厌我。

基本上,我正在尝试从https://owapi.net/api/v3/u/Xvs-1176/blob 获取信息并使用 JSON 结果来获取有关用户的基本信息。但是每当我尝试使用 file_get_contents 时,它都会返回

Warning: file_get_contents(https://owapi.net/api/v3/u/Xvs-1176/blob): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD REQUEST in Z:\DevProjects\Client Work\Overwatch Boost\dashboard.php on line

所以我不知道到底出了什么问题。我的代码可以在这里看到:

$apiBaseURL = "https://owapi.net/api/v3/u";
$apiUserInfo = $gUsername;
$apiFullURL = $apiBaseURL.'/'.$apiUserInfo.'/blob';

$apiGetFile = file_get_contents($apiFullURL);

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 你能在调用 file_get_contents 之前回显 $apiFullURL 吗?
  • 您缺少一些它期望的标题(猜测),在本地测试相同的结果,尝试 curl()
  • 400 是一个错误的请求错误,这意味着您可能没有提供请求所期望的标头或其他数据
  • @vicatcu 是的,它回显“owapi.net/api/v3/u/Xvs-1176/blob”。

标签: php json


【解决方案1】:

您需要像这样为 file_get_contents 设置用户代理,您可以使用此代码检查它。参考 this 为 file_get_contents 设置用户代理。

<?php
$options  = array('http' => array('user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:53.0) Gecko/20100101 Firefox/53.0'));
$context  = stream_context_create($options);
$response = file_get_contents('https://owapi.net/api/v3/u/Xvs-1176/blob', false, $context);
print_r($response);                  

【讨论】:

  • 如果 $gUsername = "Xvs-1176",这与 OP 所做的有何不同?
  • @vicatcu 我已经编辑并检查了它。你现在可以检查一下。感谢您的评论。
  • 正如@vicatcu 所说,这绝对是标题问题。非常感谢你们的回答:D
【解决方案2】:

这就是页面发送的内容:“嗨!为防止滥用此服务,您需要自定义用户代理”。 您可以像这样使用 curl 自定义它:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://owapi.net/api/v3/u/Xvs-1176/blob"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); 
$output = curl_exec($ch);   

$output = json_decode($output);

if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
  var_dump($output);
}

curl_close($ch);

【讨论】:

  • 我得到的只是 "Z:\DevProjects\Client Work\Overwatch Boost\dashboard.php:89:" 和 null。
  • @SDC 哦,是的,你必须使用 $output 变量
  • @SDC 只是 print_r($output);
  • @SDC 我已经在 $output = json_decode($output) 时为您解码了 json。如果这不是您想要的行为,请删除此字符串。
【解决方案3】:

如果您执行curl -v https://owapi.net/api/v3/u/Xvs-1176/blob,您将收到响应并且您将看到默认情况下 cURL 包含哪些标头。即:

> Host: owapi.net
> User-Agent: curl/7.47.0
> Accept: */*

那么问题来了,owapi 关心的是哪一个?好吧,您可以像这样阻止 cURL 发送默认标头:

curl -H "Accept:" -H "User-Agent:" -H "Host:" https://owapi.net/api/v3/u/Xvs-1176/blob

...您确实会收到 400 响应。实验上,如果你去掉“Host”或“User-Agent”标题,你会得到以下结果:

{"_request": {"api_ver": 3, "route": "/api/v3/u/Xvs-1176/blob"}, "error": 400, "msg": "Hi! To prevent abuse of this service, it is required that you customize your user agent."}

事实证明,您实际上并不需要“Accept”标头。请参阅 PHP docs,了解如何将标头与 file_get_contents 一起发送。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2015-03-23
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2019-03-24
    相关资源
    最近更新 更多