【问题标题】:Translator Text API | Microsoft Azure | Always ERROR 401000文本翻译 API |微软天青 |总是错误 401000
【发布时间】:2020-05-03 11:05:23
【问题描述】:

我尝试测试 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."}}"

错在哪里?我应该在开发者门户等上启用任何设置吗?

【问题讨论】:

  • 你能修复它吗?

标签: azure php-curl microsoft-translator bing-translator-api


【解决方案1】:

也许这会有所帮助。在官方documentation 中,您可以找到两个 CURL 请求示例。两者的区别在于第二个也有参数region。在我的情况下,只有第二个请求有效。也许 region 参数是必不可少的。

【讨论】:

  • 我可以确认我之前的回答。我在使用 Python 时遇到了同样的问题,一旦我将 'Ocp-Apim-Subscription-Region' 添加到 CURL 标头中,API 就可以正常工作了。
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多