A Generic Method Using HttpClient to Make a Synchronous Get Request
A while back I wrote a post on how to make an HTTP Get request using the HttpWebRequest object in .NET, implemented in a Generic method. Last week I had two occasions during which to revisit this code, but using the HttpClient class introduced in .NET 4.5 instead. The code below is functionally similar to the code in my earlier post, but uses HttpClient instead of HttpWebRequest.
A few points of interest:
public T ExecuteGet( string url)
A few points of interest:
- The HttpClient.GetAsync() method returns a Task that is executed asynchronously (hence the name), however, calling the Result property of that Task ensures that the asynchronous operation is complete before returning. By accessing it off of the GetAsync() return value as shown below, we are essentially blocking and changing the call into a synchronous one.
- The EnsureSuccessStatusCode() method of the HttpResponseMessage class will throw an exception of the response does not indicate success.
public T ExecuteGet
{
if (String.IsNullOrWhiteSpace( url))
throw new ArgumentException("url is required.");
using (var client = new HttpClient())
{
HttpResponseMessage response = client.GetAsync(url).Result;
response. EnsureSuccessStatusCode();
if (response.Content == null)
return default(T);
DataContractSerializer serializer = new DataContractSerializer(typeof( T));
var obj = serializer.ReadObject( response.Content. ReadAsStreamAsync().Result);
return (T)obj;
}
}
Comments
Post a Comment