gpt4 book ai didi

php - mobile.de 搜索 api 授权 fehler mit PHP curl

转载 作者:可可西里 更新时间:2023-11-01 00:45:34 25 4
gpt4 key购买 nike

我尝试从 "mobile.de Search API" 获取数据, 但它不起作用 =/.. 每次都会出现此错误:

HTTP Status 401 - This request requires HTTP authentication ().

..我做错了什么?

$authCode = base64_encode("{Benutzername}:{Passwort}");
$uri = 'http://services.mobile.de/1.0.0/ad/search?modificationTime.min=2012-05-04T18:13:51.0Z';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('Authorization: '.$authCode,'Accept-Language: de','Accept: application/xml'),
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
echo $out;

据我所知,我完全符合接口(interface)描述。

最佳答案

您需要设置以下 curl 选项以获得正确的授权:

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); // HTTP Basic Auth
curl_setopt($curl, CURLOPT_USERPWD, $username.":".$password); // Auth String

我的实现的简化版本:

<?

class APIProxy {
/* The access proxy for mobile.de search API */
private $username;
private $password;
private $api_base;

function __construct(){
/* Auth Data */
$this->username = '{username}';
$this->password = '{password}';
$this->api_base = 'http://services.mobile.de/1.0.0/';
}

function execute($query){
/* executes the query on remote API */

$curl = curl_init($this->api_base . $query);
$this->curl_set_options($curl);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl);

if($curl_error){ /* Error handling goes here */ }

return $response;
}

function get_auth_string(){
/* e.g. "myusername:mypassword" */
return $this->username.":".$this->password;
}

function curl_set_options($curl){
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ); // HTTP Basic Auth
curl_setopt($curl, CURLOPT_USERPWD, $this->get_auth_string()); // Auth String
curl_setopt($curl, CURLOPT_FAILONERROR, true); // Throw exception on error
curl_setopt($curl, CURLOPT_HEADER, false); // Do not retrieve header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Retrieve HTTP Body
}

}

$api = new APIProxy();
$result = $api->execute('ad/search?interiorColor=BLACK');
echo $result;
?>

关于php - mobile.de 搜索 api 授权 fehler mit PHP curl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19871169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com