Skip to content

Instantly share code, notes, and snippets.

@JsAndDotNet
Last active December 8, 2021 10:24
Show Gist options
  • Save JsAndDotNet/fbb11818fddf77bda060130553c4797d to your computer and use it in GitHub Desktop.
Save JsAndDotNet/fbb11818fddf77bda060130553c4797d to your computer and use it in GitHub Desktop.
HttpClient API Call
public void SendData(string authToken, MyDataClass myData)
{
try
{
var url = $"https://www.something.com/api/something/post";
HttpClient client = new HttpClient();
//client.BaseAddress = new Uri(url);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authToken);
var json = JsonSerializer.Serialize(myData);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
// List data response.
// asncy would be
// HttpResponseMessage response = await client.PostAsync(url, httpContent);
HttpResponseMessage response = client.PostAsync(url, httpContent).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body (usually a json string).
var respData = response.Content.ReadAsStringAsync().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
var resObj = JsonSerializer.Deserialize<SuccessResponseClass>(respData);
}
else
{
var errStr = response.Content.ReadAsStringAsync().Result;
// Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
var errorRespObj = JsonSerializer.Deserialize<ErrorResponseClass>(errStr);
}
// Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment