Home
> Uncategorized > Microsoft Translation #API using #Azure #CognitiveServices
Microsoft Translation #API using #Azure #CognitiveServices

When it comes to translation APIs, then Google translate is perhaps the first that comes to mind, but there is also Microsoft Azure translation API, under their cognitive Services umbrella.
Here is some simple code to implement the API, – I’ve omitted my API keys, and assuming you are using the WesternEurope (Ireland) endpoint.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
const string strUrl = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es&from=en";
var wc = new WebClient();
wc.Headers["Ocp-Apim-Subscription-Key"] = key;
wc.Headers["Ocp-Apim-Subscription-Region"] = "westeurope";
wc.Encoding = Encoding.UTF8;
var jPost = new [] { new { Text = "Hello, what is your name?"}};
var strPost = JsonConvert.SerializeObject(jPost, Formatting.Indented);
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
var json = "";
try
{
json = wc.UploadString(strUrl, "POST", strPost);
}
catch (WebException exception)
{
string strResult = "";
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
strResult = reader.ReadToEnd();
}
}
}
throw new Exception(strResult);
}
var jResponse = JArray.Parse(json);
var translation = jResponse.First["translations"].First["text"].ToString();
It also requires the Newtonsoft.JSON Nuget package.
Hope this is useful to someone.
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback