我正在尝试使用HTTP基本身份验证从API中提取数据。对API的HTTP请求受HTTP基本身份验证保护。 HTTP基本身份验证由令牌和密钥组成。
我尝试了许多不同的技术,但不断获得未提供身份验证的响应。我不确定令牌:secret方法是否与用户名:密码不同但我无法通过身份验证进行验证。
stdClass对象 ( [error_message] =>未提供身份验证。 )
以下是API文档 - https://www.whatconverts.com/api/
<?php
$token = "xxx";
$secret = "yyy";
$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_HTTPAUTH => "CURLAUTH_BASIC", // authentication method
CURLOPT_USERPWD => "$token:$secret", // authentication
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>
答案 0 :(得分:3)
这是错误的:
CURLOPT_HTTPAUTH => "CURLAUTH_BASIC", // authentication method
^^^^^^^^^^^^^^^^
这是一个字符串,而不是卷曲常量。尝试
CURLOPT_HTTPAUTH => CURLAUTH_BASIC, // authentication method
代替。
区别在于:
define('FOO', 'bar');
echo FOO // outputs bar
echo "FOO" // outputs FOO
答案 1 :(得分:0)
您需要将全局变量传递到本地范围。要做到这一点......
变化:
function get_web_page($url) {
要:
function get_web_page( $url, $token, $secret ) {
并改变:
$response = get_web_page("https://leads.seekmomentum.com/api/v1/leads");
要:
$response = get_web_page( "https://leads.seekmomentum.com/api/v1/leads", $token, $secret );
和
删除CURLAUTH_BASIC周围的引号 - 它是一个常量,而不是一个值。 (帽子提示@iainn)