且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mobile.de search api Authorization fehler mit PHP curl

更新时间:2023-12-03 20:43:58

您需要设置以下 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;
?>