我的 PHP Curl 代码没有返回错误或任何响应文本。我基于它的 JavaScript 代码返回一个 Json 数组。
header('Access-Control-Allow-Origin: ' . $_SERVER['SERVER_NAME']);
$subscriptionKey = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://southcentralus.tts.speech.microsoft.com/cognitiveservices/voices/list');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Ocp-Apim-Subscription-Key", $subscriptionKey));
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if($response === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors<br>';
echo "Response: $response";
}
$voices = json_decode($response);
curl_close($ch);
var request = new XMLHttpRequest();
var subscriptionKey = '';
request.open('GET', 'https://southcentralus.tts.speech.microsoft.com/cognitiveservices/voices/list', true);
request.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
const response = this.response;
const data = JSON.parse(response);
console.log(data);
} else {
window.console.log(this);
}
};
request.send()
我将 CURLOPT_HEADER
更改为 true(感谢 Lucas 的评论),现在收到 401 错误。这让我很困惑,因为它是完全相同的 URL 和订阅密钥。
答案 0 :(得分:1)
CURLOPT_HTTPHEADER
的数组每个标题采用一项,而不是键和值的单独项。因此,在这种情况下,请尝试:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Ocp-Apim-Subscription-Key: $subscriptionKey"));