php - 将 file_get_contents 与基本身份验证和 SSL 一起使用
问题描述
我正在尝试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;
这是我收到的错误消息:
警告: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;
事实是服务器不支持 HTTP/1.0。所以你对 SSL/TLS 和你的用户代理没有任何问题。它只是从 1.1 开始支持 HTTP 的服务器。
正如stream_context_create文档中所说, stream_context_create中使用的默认协议版本是 1.0。这就是您收到错误 500 的原因。
推荐阅读
- javascript - Javascript函数范围和执行上下文
- youtube - Youtube 嵌入链接 - 删除标题,稍后观看,分享链接?
- gnuplot - gnuplot 空 y 范围/在 0 处绘制数据
- winforms - 在 Windows 窗体应用程序中输入缓慢的问题
- android - WebRTC如何在Android中静音本地音频播放?
- python - Python中的非重复颜色和特定线宽
- scheme - Chez Scheme:顶层的宏导入
- javascript - 需要检查用户输入是否为数字。代码未按预期工作。有人可以告诉我有什么问题吗?
- swift - String(contentsOf: URL) 返回“没有这样的文件或目录”
- python - 如何使用 np.where 返回 2D numpy 数组中所有位置为零的元组列表?