/
program.cs
70 lines (54 loc) · 2.64 KB
/
program.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
67
68
69
70
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Http;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
Console.Write("Enter the path to a JPEG image file:");
string imageFilePath = Console.ReadLine();
MakeRequest(imageFilePath);
Console.WriteLine("\n\n\nWait for the result below, then hit ENTER to exit...\n\n\n");
Console.ReadLine();
}
static byte[] GetImageAsByteArray(string imageFilePath)
{
FileStream fileStream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
static async void MakeRequest(string imageFilePath)
{
var client = new HttpClient();
// Request headers - replace this example key with your valid key.
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "2e4167d9f21e432686ee677952e39cf4");
// NOTE: You must use the same region in your REST call as you used to obtain your subscription keys.
// For example, if you obtained your subscription keys from westcentralus, replace "westus" in the
// URI below with "westcentralus".
string uri = "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize?";
HttpResponseMessage response;
string responseContent;
// Request body. Try this sample with a locally stored JPEG image.
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (var content = new ByteArrayContent(byteData))
{
// This example uses content type "application/octet-stream".
// The other content types you can use are "application/json" and "multipart/form-data".
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
responseContent = response.Content.ReadAsStringAsync().Result;
}
// System.IO.File.WriteAllText(@"C:\test\test1.json", responseContent);
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(@"C:\test\test1.json", true))
{
file.WriteLine(responseContent);
}
//A peak at the JSON response.
Console.WriteLine(responseContent);
}
}
}