使用 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)."rn".
                  "Content-Type: application/json",
);

最新更新