Skip to content

Instantly share code, notes, and snippets.

@redent
Created July 15, 2013 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redent/6000294 to your computer and use it in GitHub Desktop.
Save redent/6000294 to your computer and use it in GitHub Desktop.
REST Get/Post Sample using HttpClient with async/await and JSON content
private readonly IMvxJsonConverter _converter;
public async Task<T> GetAsync<T>(string url, CancellationToken cancellationToken) where T : new()
{
var client = new HttpClient();
var response = await client.GetAsync(url, cancellationToken);
var responseString = await response.Content.ReadAsStringAsync();
var result = _converter.DeserializeObject<T>(responseString);
return result;
}
public async Task<T> PostAsync<T>(string url, object postContent, CancellationToken cancellationToken) where T : new()
{
var client = new HttpClient();
var serializedContent = _converter.SerializeObject(postContent);
HttpContent httpContent = new StringContent(serializedContent, Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, httpContent, cancellationToken);
var responseString = await response.Content.ReadAsStringAsync();
var result = _converter.DeserializeObject<T>(responseString);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment