问题
I tried to test Microsoft Translator API Text v3.0 but failed with 401 Access denied. I do standard cURL requests (HTTP POST) using PHP 7.3.
$key = "************************"; // secret key here (from the Azure Portal)
$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";
$params = "&to=en&from=bg";
$text = "За мен лично хора, които задават такива въпроси са несъобразителни.";
$requestBody = array(
array(
'Text' => $text,
),
);
$content = json_encode($requestBody);
if (!function_exists('com_create_guid')) {
function com_create_guid()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}
$curl_headers = array(
'Content-type: application/json',
'Content-length: ' . strlen($content),
'Ocp-Apim-Subscription-Key: ' . $key,
'X-ClientTraceId: ' . com_create_guid()
);
$url = $host . $path . $params;
$ch = curl_init();
$curl_content = array('content', $content);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
$result = curl_exec($ch);
//dd(curl_getinfo($ch, CURLINFO_HEADER_OUT));
if (curl_exec($ch) === false) {
dd(curl_error($ch));
}
Laravel 5.6, the code is placed on api.php
route file.
Response Code:
"{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}"
Where is the mistake? Should I enable any settings on the developer portal and so on?
回答1:
Maybe this can help. In the official documentation you can find two examples of CURL requests. The difference between the two is that the second one has also the parameter region. Only the second request works in my case. Maybe the region parameter is essential.
来源:https://stackoverflow.com/questions/61573396/translator-text-api-microsoft-azure-always-error-401000