Skip to content

Instantly share code, notes, and snippets.

@pocheptsov
Created May 28, 2015 21:19
Show Gist options
  • Save pocheptsov/0ffc3573b1f76948561d to your computer and use it in GitHub Desktop.
Save pocheptsov/0ffc3573b1f76948561d to your computer and use it in GitHub Desktop.
Face detection and uploading source file to Rekognition service from C# .NET Async
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldRekognition
{
class Program
{
private const string ApiKey = "";
private const string ApiSecretKey = "";
static void Main()
{
Call().ContinueWith(task => Console.WriteLine(task.Result));
Console.ReadLine();
}
private static async Task<string> Call()
{
var data = new Dictionary<string, string>
{
{"api_key", ApiKey},
{"api_secret", ApiSecretKey},
{"jobs", "face_gender_age_emotion_recognize"},
{"base64", Convert.ToBase64String(File.ReadAllBytes("people.jpg"))}
};
var content = new BodyFormUrlEncodedContent(data);
var request = new HttpRequestMessage
{
Content = content,
Method = HttpMethod.Post,
RequestUri = new Uri("https://rekognition.com/func/api/")
};
var httpClient = new HttpClient();
var sendTask = await httpClient.SendAsync(request);
var response = await sendTask.Content.ReadAsStringAsync();
return response;
}
}
public class BodyFormUrlEncodedContent : ByteArrayContent
{
public BodyFormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
: base(GetContentByteArray(nameValueCollection))
{
Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
}
private static byte[] GetContentByteArray(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
{
if (nameValueCollection == null)
{
throw new ArgumentNullException("nameValueCollection");
}
StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<string, string> current in nameValueCollection)
{
if (stringBuilder.Length > 0)
{
stringBuilder.Append('&');
}
stringBuilder.Append(Encode(current.Key));
stringBuilder.Append('=');
stringBuilder.Append(Encode(current.Value));
}
return Encoding.Default.GetBytes(stringBuilder.ToString());
}
private static string Encode(string data)
{
if (string.IsNullOrEmpty(data))
{
return string.Empty;
}
return (WebUtility.UrlEncode(data) ?? string.Empty).Replace("%20", "+");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment