Accessing Azure Translation API using Single Token – Sample Java Snippet

Accessing API using ClientSecret and ClientID will be decommissioned after April 30,2017.

Previously

//Setting ClientID and ClientSecret obtained from Azure Portal
Translate.setClientId(CLIENT_ID);
Translate.setClientSecret(CLIENT_SECRET);
//Azure API Call
translatedText = Translate.execute(textToTranslate, Language.AUTO_DETECT,Language.ENGLISH);

Now – Instead of ClientID and Secret code we need to use single Access Token.
Using this, we need to generate a key and then use it for translation.

Following Sample Java code uses the sample token to generate a key, and then using the key we are accessing API

String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
authConn.setRequestMethod("POST");
authConn.setDoOutput(true);
//Adding for size 0
authConn.setFixedLengthStreamingMode(0);
//Supply KEY obtained from Azure portal
authConn.setRequestProperty("Ocp-Apim-Subscription-Key", AUTH_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");
//Provide text to translate
String text = URLEncoder.encode(textToTranslate, "UTF-8");
//Optional - If you don't give, this will be auto detect input language
String from = "fr";
String to = "en";
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");
//Response will be in XML, to get the converted text , use the root element. Print response and change schema string if required
String convertedText = (resp.split("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">")[1]
		.split("</string>")[0]);
;

 

References :

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: