azure - 文本翻译 API | 微软天青 | 总是错误 401000
问题描述
我尝试测试 Microsoft Translator API Text v3.0 但因 401 访问被拒绝而失败。我使用 PHP 7.3 执行标准 cURL 请求(HTTP POST)。
$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,代码放在api.php
路由文件中。
响应代码:
"{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}"
错误在哪里?我应该在开发者门户等上启用任何设置吗?
解决方案
也许这会有所帮助。在官方文档中,您可以找到 CURL 请求的两个示例。两者的区别在于,第二个也有参数region。在我的情况下,只有第二个请求有效。也许区域参数是必不可少的。
推荐阅读
- firebase - 如何在 Flutter 中获取、设置、更新和删除云 Firestore 中的数据?
- android - 房间数据库:NOT NULL 约束在删除时失败
- git - 为不同平台构建时 Ionic / Cordova 项目的源代码控制策略
- c# - 在类列表中对字符串 DateAndTime 值进行排序
- jenkins - 如何使用 jenkins 设置 gitlab 管道?
- android - 如何通过登录应用程序访问 laravel 控制器功能
- firebase - 为什么在集合项目上设置返回待处理的承诺
- javascript - ng-checked 不适用于角度 js 模板中的多个条件表达式
- javascript - 使用全新的 UI 设计转换现有的 Angular 应用程序
- python - 在最近的关键条件上加入 Spark DataFrame