There is one thing that most client projects have in common – they request data, in some form, from a server. When developing for Windows Phone I prefer to do these requests using HttpWebRequest instead of WebClient (why – explained here by Andreas).
But this is not a post about Windows Phone, it’s about the HttpClient that is now included in .NET Framework 4.5. Even more specifically – this post is about why HttpClient is awesome and why you’ll love it.
GET according to HttpClient
This is how you do a GET.
public async Task<JsonObject> GetAsync(string uri) { var httpClient = new HttpClient(); var response = await httpClient.GetAsync(uri); //will throw an exception if not successful response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return await Task.Run(() => JsonObject.Parse(content)); }
That’s it folks. Thanks to the new language features of C# and HttpClient we can easily do a web request asynchronously. In this example we also do a asynchronous parse of the result using into a JsonObject.
But we actually can make it even simpler.
public async Task<JsonObject> GetAsync(string uri) { var httpClient = new HttpClient(); var content = await httpClient.GetStringAsync(uri); return await Task.Run(() => JsonObject.Parse(content)); }
Three lines to do an asynchronous HTTP GET and parsing (not counting the try/catch you need to wrap this method with).
POST according to HttpClient
This is how you do a POST with some string data.
public async Task<JsonObject> PostAsync(string uri, string data) { var httpClient = new HttpClient(); response = await httpClient.PostAsync(uri, new StringContent(data)); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return await Task.Run(() => JsonObject.Parse(content)); }
As you can see it is very similar to GET. What you also notice is that it is extremely simple to add POST data (at least if you compare it to the trusty old HttpWebRequest).
Summary
HttpClient is actually available as a NuGet package that you can download today. But a lot of the simplicity of using HttpClient comes from the new language features of C# 5. Combine these two and you got a very simple way of requesting and posting data. If you want to read more details about HttpClient I recommend this post by Darrel Miller.
HttpClient – Learn it, Live it, Love it.
Great article Peter. But I have question for you. You mention about the JsonObject in you example. But I cannot find this anywhere even though I have installed JSon.Net. When I googled for it, I found this MSDN article http://msdn.microsoft.com/en-us/library/system.json.jsonobject%28v=vs.110%29.aspx which says it is part of System but even though I use Framework 4.5 I cannot find it within System namespace.
So, would you mind mentioning this in your article on how to find this JsonObject please? That would definitely help a lot of people like me who go crazy on where to find this class in what namespace and/or what are the requirements to enjoy this functionality.
Thanks,
Vincent
Vincent – Use JObject instead supported as part of Newtonsoft.Json
Vincent – from the document http://msdn.microsoft.com/en-us/library/cc626400(v=vs.95).aspx It’s a part of Silverlight framework
Vincent, perhaps try System.Json as namespace. See: http://msdn.microsoft.com/en-us/library/system.json.jsonobject(v=vs.110).aspx
hi
can you please complete the verbs put and delete and aggregate a simple of use. Please !!
thank!!
Pingback: itemprop="name">Adventures in JSON parsing with C# | Web Things Considered
Hi, if I try to use JsonObject as the return type I get errors… it only works for me if I use this code:
public static class Helper
{
public static async Task GetAsync(string uri)
{
var httpClient = new HttpClient();
var content = await httpClient.GetStringAsync(uri);
return await Task.Run(() => JsonValue.Parse(content));
}
}
Is this the same thing or is JsonValue different from JsonObject?
Pingback: itemprop="name">HttpClient, Twitter OAuth & die Twitter Timeline auslesen | Code-Inside Blog
It’s actually JObject, not JsonObject
return await Task.Run(() = JsonObject.Parse(content));
You shouldn’t do this. You should only use async await for IO bound operations. Since JsonObject.Parse is CPU bound you’re actually making it take longer and chew up more threads than needed.
Pingback: itemprop="name">Webclient VS Httpclient | Logbook
hi Jayway :)
Code nice but some encoding issue on your code. > < etc.
Pingback: itemprop="name">Web Services : Understanding C# HttpClient | abgoswam's tech blog
Pingback: itemprop="name">Web Services : WebClient vs HttpClient vs HttpWebRequest | abgoswam's tech blog
Thanks for the great article!
Just wanted to let you know that your are appearing as < and > in Chrome 56.0.2924.87
httpClient, response and content are all disposable, and must be disposed of. Much better if you put them in 3 using statements. Calling Disose() is not oprional
well talk about a worthless shit crapola post rofl
Peter von Lochow rofl sounds like something that comes out a cows ahole
Hey Peter von Lochow rofl how long you been sticking that unit inch dick of yous up the goats ahole
Nice examples – you may want to clean up the encoding in your source :-)
In Get according to HttpClient, if uri starts with https://
then, GetAsync(uri) doesn’t work.
Any solution for it ?
Your Way Of Explanation was good. You add some valuable points. Here I am sharing some information about dotnet..NET technology helps in creating applications. The versatility of the technology has been the foremost factor that allows its widespread use. The .NET software is from Microsoft. Microsoft launched this technology stating it as an advanced new platform built on highly developed protocols with tools that help in faster and better communication and computing. APec computer Institute is one of the best .Net training provides and placements dot net online training in Hyderabad. They provide real-time hands-on practical and real-time live projects Oriented training. They provide to learn, work on live projects, become dot net developer & join the top IT companies. Essential practical, assignments, real-time live Projects & interview questions by .Net experts.
dotnet online training in hyderabad