System.Net namespace contains classes for working with different network protocols such as HTTP and FTP.Starting with version 4.5,.NET Framework provides HttpClient class for requesting resources from a specific URL.It is a wrapper over HttpWebRequest and HttpWebResponse classes and provides additional functionality for working with WebAPIs and REST based services.
You can send HTTP requests and receive HTTP responses for a given URL using the HttpClient class.HttpClient is part of the System.Net.Http namespace which is in assembly System.Net.Http.dll
HttpClient is derived from the class HttpMessageInvoker base class.
To request a response for a given Web API URL follow the below steps:
- Create an instance of HttpClient class using the default constructor
HttpClient client = new HttpClient()
2. Use one of the GetAsyncXXX methods for retrieving response at a specific URL and assign the response to a variable:
string resObj = await client.GetStringAsync(URL of a web api);
There are mostly asynchronous methods for accessing the URL using different HTTP methods.In this example we have used GetAsync() method but there methods for delete,put and post as well.
WebAPI
In the following example we are creating a sample WebAPI.This is generating automatically when you create a new WebAPI project in Visual Studio:
public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } }
Access WebAPI using HttpClient.
Now we will create a console application to access the above Get method as:
try { using (HttpClient client = new HttpClient()) { string response = await client.GetStringAsync("http://localhost:14057/api/values/"); Console.WriteLine("returned value={0}", response); } } catch (Exception exp) { } }
GetAsync(Uri) Sends a GET request to the specified Uri as an asynchronous operation.
POST using HttpClient
WebAPI
public void Post([FromBody]string value) { }
Calling WebAPI POST using HttpClient
try { using (HttpClient client = new HttpClient()) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", "") }); var response = await client.PostAsync("http://localhost:14057/api/values/post/", content); Console.WriteLine("returned value={0}", response); } } catch (Exception exp) { }
Some other useful methods provided by HTTPClient are:
Request Type | Method | Use |
GET | GetAsync(String) | For sending GET request to a Uri as an asynchronously. |
GET | GetAsync(String, HttpCompletionOption) | For sending GET request to a Uri asynchronously and passes an HTTP completion option parameter. |
GET | GetAsync(String, CancellationToken) | For sending GET request to a Uri asynchronously and passes an HTTP CancellationToken parameter. |
GET | GetStreamAsync(String) | For sending GET request to a Uri asynchronously.The response body is a stream. |
GET | GetStreamAsync(Uri) | For sending GET request to a Uri asynchronously.The response body is a stream. |
POST | PostAsync(String, HttpContent) | For sending POST request to a Uri asynchronously and passes HttpContent parameter. |
POST | PostAsync(String, HttpContent, CancellationToken) | For sending POST request to a Uri asynchronously and passes HttpContent & CancellationToken parameters. |
PUT | PutAsync(String, HttpContent) | Sends a PUT request to the specified Uri as an asynchronous operation. |
PUT | PutAsync(Uri, HttpContent) | Sends a PUT request to the specified Uri as an asynchronous operation and passes HttpContent parameter.. |
DELETE | DeleteAsync(String) | For sending DELTE request to a Uri asynchronously. |
DELETE | DeleteAsync(Uri) | For sending POST request to a Uri asynchronously |
DELETE | DeleteAsync(String, CancellationToken) | For sending POST request to a Uri asynchronously and passes cancellation token as a parameter. |