簡體   English   中英

如何在 php 中使用 file_get_contents 和摘要式身份驗證訪問 REST Web 服務

[英]How to Access REST Web service using file_get_contents with Digest Authentication in php

如何在 php 中使用 file_get_contents 和 Digest Authentication 來使用 Restful API。

我知道我可以使用 curl 訪問它

$ch = curl_init('http://webservicesurlhere.com');


curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'
        //,
        //'Content-Length: ' . strlen($data_string)
        )
);

$resources = curl_exec($ch);
curl_close($ch);

但是我的當前代碼是使用 file_get_contents 編寫的,可以使用以下代碼訪問基本類型身份驗證

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

有誰知道,我如何使用file_get_contents進行摘要類型的身份驗證?

我找到的相關信息。

如何使用file_get_contents在PHP中發布數據?

在 PHP 中調用 REST API

正如您所說,使用curl的以下代碼應該可以工作:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
curl_setopt($ch, CURLOPT_USERPWD, 'user:secret');

但是,curl 會為您完成所有工作。 使用file_get_contents()您需要自己實現digest認證。 對不起,現在沒有時間准備一個例子,但我希望這有助於http://www.ietf.org/rfc/rfc2617.txt , http://freestyle-developments.co.uk/blog/?p=61 ...

也許我稍后還會在這里添加一個自定義示例,因為我一直想仔細查看摘要驗證...

這項工作通過 https 和 json 響應形成我

<?php 
 $login = 'USUARIO';
 $password = '123';
 $url = 'https://ww.google.com/datos-feps?date=13-08-2020';
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
 $result_json = curl_exec($ch);
 curl_close($ch);    
 echo $result_json;      
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM