Accessing Azure Translation API using Single Token – Sample Java Snippet

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


//Setting ClientID and ClientSecret obtained from Azure Portal
//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 = "";
HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
//Adding for size 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");
// 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("", appId, text,from, to);
HttpsURLConnection translateConn = (HttpsURLConnection) new URL(translatorTextApiUrl).openConnection();
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=\"\">")[1]


References :



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: