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