-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathDictionaryExamples.cs
66 lines (55 loc) · 2.32 KB
/
DictionaryExamples.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.Net.Http;
using System.Text;
// NOTE: Install the Newtonsoft.Json NuGet package.
using Newtonsoft.Json;
namespace TranslatorTextQuickStart
{
class Program
{
private const string key_var = "TRANSLATOR_TEXT_SUBSCRIPTION_KEY";
private static readonly string subscriptionKey = Environment.GetEnvironmentVariable(key_var);
private const string endpoint_var = "TRANSLATOR_TEXT_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);
static Program()
{
if (null == subscriptionKey)
{
throw new Exception("Please set/export the environment variable: " + key_var);
}
if (null == endpoint)
{
throw new Exception("Please set/export the environment variable: " + endpoint_var);
}
}
static string route = "/dictionary/examples?api-version=3.0";
// Translate from English to French.
static string params_ = "&from=en&to=fr";
static string uri = endpoint + route + params_;
static string text = "great";
static string translation = "formidable";
async static void Examples()
{
System.Object[] body = new System.Object[] { new { Text = text, Translation = translation } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(uri);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
var result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);
Console.OutputEncoding = UnicodeEncoding.UTF8;
Console.WriteLine(result);
}
}
static void Main(string[] args)
{
Examples();
Console.ReadKey();
}
}
}