Skip to content

Instantly share code, notes, and snippets.

@marvinosswald
Created December 6, 2018 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marvinosswald/41fea6b85eba351423dd1793f544664f to your computer and use it in GitHub Desktop.
Save marvinosswald/41fea6b85eba351423dd1793f544664f to your computer and use it in GitHub Desktop.
C# HttpClient example
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace httpclientTest
{
public class Program
{
static HttpClient client = new HttpClient();
static async Task<String> GetResourceAsync (string path)
{
String body = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
body = await response.Content.ReadAsStringAsync();
}
return body;
}
static async Task RunAsync()
{
// Update port # in the following line.
client.BaseAddress = new Uri("https://baconipsum.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
String resource = null;
try
{
// Get the product
resource = await GetResourceAsync("api/?type=meat-and-filler");
Console.WriteLine(resource);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment