【问题标题】:Call ODATA service with PHP file_get_contents使用 PHP file_get_contents 调用 ODATA 服务
【发布时间】:2026-02-04 04:45:01
【问题描述】:

我需要在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

我也有用户名和密码,但是不知道怎么用。

【问题讨论】:

    标签: php odata file-get-contents


    【解决方案1】:

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

    【讨论】: