3

我试图从“mobile.de Search API”获取数据,但它不起作用=/ ..这个错误每次都会出现:

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;

据我所知,我已经完全遵守了接口说明。

4

2 回答 2

5

您需要设置以下 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;
?>
于 2013-11-10T14:25:02.157 回答
0

一个非常基本的非面向对象的方法是使用带有操纵头的文件获取内容来访问搜索 API。我分享它是为了给出一个非常简单的例子,如何使用 mobile.de API。但是,请记住 file_get_contents 可能比 curl 慢 30% - 50%。

    ### Set language property in header (e.g. German) ###
    $opts = array(
    'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: de\r\n" 
        )
    );

    $baseURL = 'http://<<username>>:<<password>>@services.mobile.de/1.0.0/ad/search?';

    $searchURL .= $searchString; ## provide get parameters e.g. color=red&make=bmw

    ##fetch your results
    $file = file_get_contents($searchURL, false, $context);

关于授权数据。Mobile.de 为每个经销商免费提供。只需在您的经销商仪表板中生成身份验证属性。

于 2016-01-29T12:03:53.910 回答