PHP中的新Bing API不支持的身份验证

时间:2012-08-06 09:09:45

标签: php azure bing-api

我一直在将旧的Bing API中的应用程序移植到新的应用程序中。看过几篇关于新版如何在PHP中工作的帖子我发现了身份验证问题。

这是网址返回的错误:

Warning: file_get_contents(https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query=%27%27) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 401 The authorization type you provided is not supported. Only Basic and OAuth are supported in /home/krem81/public_html/classes/class.BingSearch.php on line 178

反过来,这是我用来与API交互的函数:

$accountKey = $this->Appid;

$ServiceRootURL =  "https://api.datamarket.azure.com/Bing/Search/";

$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';

$context = stream_context_create(array(
    'http' => array(
        'request_fulluri' => true,
        'header'  => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
    )
));

$request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');

echo($request);

$this->response = file_get_contents($request, 0, $context);

$this->results = json_decode($this->response);

自从尝试这个以来我现在也尝试了

    $accountKey = $this->Appid;

    $ServiceRootURL =  "https://api.datamarket.azure.com/Bing/Search/";

    $WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query=';

    $request = $WebSearchURL . urlencode( '\'' . $this->keyword . '\'');

    echo($request);

    $process = curl_init($request);
    curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($process, CURLOPT_USERPWD,  $accountKey . ":" . $accountKey);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);

    $this->response = curl_exec($process);

    var_dump($this->response);

    $this->results = json_decode($this->response);

    var_dump($this->results);

有没有人对触发身份验证失败的内容有任何想法?

3 个答案:

答案 0 :(得分:1)

以下是Search API的工作示例,只需将您的访问密钥替换为“XXXX”即可。即使我浪费了几个小时才能使用cURL工作,但它在本地出现“CURLOPT_SSL_VERIFYPEER”失败:(

$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, "username:XXXX");
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);

# Deliver
return $response;

# Have a great day!
curl_close($process);

答案 1 :(得分:0)

另一个团队成员更改了一个变量的名称,我想我应该立即检查。 $this->Appid应该是$this->APPID

正如我在评论中对ManseUK说的那样,虽然微软可以为丢失的应用程序ID提供更好的错误消息,但是有些“无效的appid”有助于缩小问题范围

答案 2 :(得分:0)

减少交通和提高速度的建议:
添加Accept-Encoding: gzip并删除身份验证中的名称。你只需要base64_encode(':' . $this->APPID)