Skip to content

Instantly share code, notes, and snippets.

@sdurandeu
Last active July 5, 2017 00:25
Show Gist options
  • Select an option

  • Save sdurandeu/61f9ef350af679b54d10c5d70a56888a to your computer and use it in GitHub Desktop.

Select an option

Save sdurandeu/61f9ef350af679b54d10c5d70a56888a to your computer and use it in GitHub Desktop.
Http Client Examples
// HIGHLIGHTS:
// - the httpclient should not be created on every request, it should be static
// - HttpCompletionOption.ResponseHeadersRead to return before downloading the full file
// see https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
// "HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Especially in server applications, creating a new HttpClient instance for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors."
namespace TryAzureCdn.WorkerRole
{
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure;
public class FileDownloadTestRunner
{
private static readonly HttpClient HttpClient = new HttpClient();
public async Task<IList<Metric>> GenerateMetricsAsync(string url, bool isCdn)
{
var fileToWriteTo = Path.GetTempFileName();
using (HttpResponseMessage response = await HttpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
}
}
}
}
}
// HIGHLIGHTS:
// - use httpClient.BaseAddress to avoid issues with final backslash
// - PostAsJsonAsync is extesion method from System.Net.Http.Formatting namespace (Microsoft.AspNet.WebApi.Client.5.2.3 NuGet)
namespace HelpDeskBot.Services
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Configuration;
using Newtonsoft.Json;
[Serializable]
public class TextAnalyticsService
{
public async Task<double> Sentiment(string text)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://westus.api.cognitive.microsoft.com/");
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", WebConfigurationManager.AppSettings["TextAnalyticsApiKey"]);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var sentimentRequest = new SentimentRequest()
{
Documents = new List<SentimentDocument>()
{
new SentimentDocument(text)
}
};
string uri = "/text/analytics/v2.0/sentiment";
var response = await httpClient.PostAsJsonAsync<SentimentRequest>(uri, sentimentRequest);
var responseString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<TextAnalyticsResult>(responseString);
if (result.Documents.Length == 1)
{
return result.Documents[0].Score;
}
return double.NaN;
}
}
internal class TextAnalyticsResult
{
public TextAnalyticsResultDocument[] Documents { get; set; }
}
internal class TextAnalyticsResultDocument
{
public string Id { get; set; }
public double Score { get; set; }
}
internal class SentimentRequest
{
public SentimentRequest()
{
this.Documents = new List<SentimentDocument>();
}
public List<SentimentDocument> Documents { get; set; }
}
internal class SentimentDocument
{
public SentimentDocument()
{
this.Language = "en";
this.Id = "single";
}
public SentimentDocument(string text)
: this()
{
this.Text = text;
}
public string Language { get; set; }
public string Id { get; set; }
public string Text { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment