Created
December 6, 2018 13:14
-
-
Save marvinosswald/41fea6b85eba351423dd1793f544664f to your computer and use it in GitHub Desktop.
C# HttpClient example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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