首页 > 解决方案 > 使用 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

我也有用户名和密码,但我不知道如何使用它们。

标签: phpodatafile-get-contents

解决方案


您需要在标题中添加“授权”。
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",
);

推荐阅读