本文介绍了mobile.de search api Authorization fehler mit PHP curl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试从 "mobile.de Search API" 获取数据,但它不起作用=/.. 每次都会出现这个错误:
I tryed to get data from the "mobile.de Search API", but it doesn't work =/ .. this error cames every time :
HTTP 状态 401 - 此请求需要 HTTP 身份验证 ().
...我做错了什么?
$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;
据我所知,我完全遵守了界面描述.
As far as I can tell, I have complied with the interface description fully.
推荐答案
您需要设置以下 curl 选项以获得正确的授权:
You need to set the following curl options for a correct authorization:
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;
?>
这篇关于mobile.de search api Authorization fehler mit PHP curl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!