Microsoft Translator API Java, How to get client new ID with Azure

后端 未结 2 1073
一向
一向 2020-12-11 10:33

Translate.setClientId(\"something\"); Translate.setClientSecret(\"something1\");

I had previously ran my code successfully using the following syntax, however, 50% o

相关标签:
2条回答
  • 2020-12-11 10:51

    You can to sign in through https://www.microsoft.com/cognitive-services

    Then, you'll find a list of keys for all services under cognitive services:

    0 讨论(0)
  • 2020-12-11 10:55

    As the information from the old offical site(for translator speech & text api) & Announcements said, "THE MICROSOFT TRANSLATOR API IS NOW AVAILABLE ON THE AZURE PORTAL" and "Action Required before April 30, 2017 - Microsoft Translator Moves to Azure". So if you want to use the Translator API now, you need to have an Azure subscription and create a Translator account of Azure Cognitive service like the offical tutorial said.

    For example using Translator Text API, you can follow the new tutorial to get an access token to build an appid for the API like my sample code in Java below.

    // Get the access token
    // The key got from Azure portal, please see https://docs.microsoft.com/en-us/azure/cognitive-services/cognitive-services-apis-create-account
    String key = "<your translator account key>";
    String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
    HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
    authConn.setRequestMethod("POST");
    authConn.setDoOutput(true);
    authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
    IOUtils.write("", authConn.getOutputStream(), "UTF-8");
    String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");
    System.out.println(token);
    
    // Using the access token to build the appid for the request url
    String appId = URLEncoder.encode("Bearer "+token, "UTF-8");
    String text = URLEncoder.encode("happy birthday", "UTF-8");
    String from = "en";
    String to = "fr";
    String translatorTextApiUrl = String.format("https://api.microsofttranslator.com/v2/http.svc/Translate?appid=%s&text=%s&from=%s&to=%s", appId, text, from, to);
    HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
    translateConn.setRequestMethod("GET");
    translateConn.setRequestProperty("Accept", "application/xml");
    String resp = IOUtils.toString(translateConn.getInputStream(), "UTF-8");
    System.out.println(resp);
    

    Hope it helps. Any concern, please feel free to let me know.

    0 讨论(0)
提交回复
热议问题