Created
May 30, 2019 03:39
-
-
Save AsishP/0ffee889c196fd992ed1a7a446cbf140 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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