Dav*_*nes 0 php file-get-contents
我正在尝试GET
使用 SSL 和使用以下file_get_contents
功能的基本身份验证请求:
$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";
$url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api";
$context = stream_context_create(array("http" => array("header" => "Authorization: Basic " . base64_encode("$username:$password"))));
$data = file_get_contents($url, false, $context);
echo $data;
Run Code Online (Sandbox Code Playgroud)
这是我收到的错误消息:
警告:file_get_contents( https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api ):无法打开流:HTTP 请求失败的!HTTP/1.0 500 服务器错误...
我已经确认openssl
已启用:
我们不妨提前解决这个问题:
为什么不直接使用 cURL?
我可以。但我也想弄清楚为什么file_get_contents
不起作用。我喜欢file_get_contents
. 叫我疯了。
好奇心是一件好事,所以在解决这个问题之前挖掘这个问题而不回到 cURL 是很酷的。
<?php
$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";
$url = "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api";
$context = stream_context_create(array(
"http" => array(
"header" => "Authorization: Basic " . base64_encode("$username:$password"),
"protocol_version" => 1.1, //IMPORTANT IS HERE
)));
$data = file_get_contents($url, false, $context);
echo $data;
Run Code Online (Sandbox Code Playgroud)
事实是服务器不支持 HTTP/1.0。所以你对 SLL/TLS 和你的用户代理都没有任何问题,没有类似的问题。它只是支持 HTTP/1.1 的服务器。
如果它适用于我们的网络浏览器,那是因为它们也使用 HTTP/1.1。
正如在所述stream_context_create文档的默认PROTOCOL_VERSION中使用stream_context_create为1.0。这就是您收到错误 500 的原因。
注意:在此示例中,我收到 401,这是因为我的凭据错误。这意味着我成功访问了服务器,如果我的凭据有效,一切都会好起来的。