Created
July 15, 2013 14:19
-
-
Save redent/6000294 to your computer and use it in GitHub Desktop.
REST Get/Post Sample using HttpClient with async/await and JSON content
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
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