Translator Text API | Microsoft Azure | Always ERROR 401000

冷暖自知 提交于 2020-07-21 04:07:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!