php - 使用 PHP file_get_contents 调用 ODATA 服务
问题描述
我需要在 Debian 9 下使用 php7.0 调用 ODATA 服务。
我正在尝试使用“file_get_contents”函数,但是当我运行脚本时
$call_opts=array(
"http"=>array(
"method"=>"GET",
"header"=>"Content-type: application/x-www-form-urlencoded",
)
);
//
$call_context=stream_context_create($call_opts);
$call_res_json=file_get_contents($url,false);
它返回以下内容:
Warning: file_get_contents(http://<URL>): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
我也有用户名和密码,但我不知道如何使用它们。
解决方案
您需要在标题中添加“授权”。
HTTP 授权请求标头包含验证用户的凭据。
Authorization: Basic <credentials>
如果使用“基本”身份验证方案,则凭证的构造如下:
- 用户名和密码用冒号组合 (aladdin:opensesame)。
- 生成的字符串采用 base64 编码 (YWxhZGRpbjpvcGVuc2VzYW1l)。
试试这个代码:
$username="auth_username";
$password="auth_password";
$call_opts=array(
"http"=>array(
"method"=>"GET",
"header"=>"Authorization: Basic ".base64_encode($username.":".$password)."\r\n".
"Content-Type: application/json",
);
推荐阅读
- usb - 如何理解使用 libusb 进行批量传输
- ios - didSet 属性值只出现在 print()
- sql - 查询以获取在 3 列中具有相同值且在 1 列中具有不同值的行
- dart - Dartdoc 找不到任何要记录的库
- r - 如何从模型中提取公式并用于 R 中的另一个模型?
- mongodb - 如何在位置数组上创建 2DSphere 索引?
- java - 在执行 java 代码时,我遇到了错误。请帮我解决这个问题
- google-bigquery - 如何从 Google BigQuery 中的非唯一记录生成唯一 ID
- c - GtkRevealer 使文本视图绘图出现故障
- ios - StackView 内的 CollectionView