Skip to content

Instantly share code, notes, and snippets.

@AsishP
Created May 30, 2019 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AsishP/0ffee889c196fd992ed1a7a446cbf140 to your computer and use it in GitHub Desktop.
Save AsishP/0ffee889c196fd992ed1a7a446cbf140 to your computer and use it in GitHub Desktop.
public string getTranslatedText(string text)
{
string host = "https://api.cognitive.microsofttranslator.com";
string route = "/translate?api-version=3.0&to=en";
string translatedText = "";
System.Object[] body = new System.Object[] { new { Text = text } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Set the method to POST
request.Method = HttpMethod.Post;
// Construct the full URI
request.RequestUri = new Uri(host + route);
// Add the serialized JSON object to your request
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
// Add the authorization header
request.Headers.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["TranslatorTextSubKey"]);
// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
// Print the response
log.Info(jsonResponse);
JArray result = JArray.Parse(jsonResponse);
log.Info(result[0].ToString());
TranslatedResult translatorObj = JsonConvert.DeserializeObject<TranslatedResult>(result[0].ToString());
foreach(var translate in translatorObj.Translations)
{
log.Info($"Translate text {translate.Text}");
translatedText = translate.Text;
}
}
return translatedText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment