WebClient Request in .Net Appliaction

Dealing with multiple platform application with a centralize data will require you to use Cloud Base Services. This is where Web API’s and Web Service come’s in. There are different kind of packages that will handle such request and one of it is the WebClient.

Below is the common HTTP request that is most used in .Net Application. I have listed all this Implementation for my future reference and to help others who are googling for these answers.

To use WebClient request we need to import this reference (System.Net.WebClient).

System.Net.WebClient – For me, this is the easiest way to download and upload data from and to a Web APIHere are a few codes to implement Web Client in 4 different methods.

WebClient Requests:

  • using System.Net;

Method: GET

WebClient can also download files, which can be found in the System.Net namespace, it downloads web pages and files. This class makes it possible to download web pages for testing easily.

string url = "http://api/service";
 using (var client = new WebClient())
         {
                    client.Headers.Add("content-type", "application/json");
                    string response = client.DownloadString(url);
         }

Method: POST

This method uploads specified string to the specified resource.

string param = "{"data1":"value1","data2":"value2"}";
 string url = "http://api/service";
            using (var client = new WebClient())
            {
                client.Headers.Add("content-type", "application/json");
                string response = Encoding.ASCII.GetString(client.UploadData(url, "POSstriT", Encoding.UTF8.GetBytes(param)));
            }

Method: DELETE

string url = "http://api/service";
            using (var client = new WebClient())
            {
                client.Headers.Add("content-type", "application/json");
               var response = Encoding.ASCII.GetString(client.UploadValues(url, "DELETE", new NameValueCollection()));
            }

Method: PUT

string param = "{"data1":"value1","data2":"value2"}";
 string url = "http://api/service";
            using (var client = new WebClient())
            {
                client.Headers.Add("content-type", "application/json");
                string response = client.UploadString(url, "PUT", param);
            }

Hopes this reference help you! Just let me know if I’m missing something. Thank you for visiting. For more article you can visit my blog page. Blog

Here is an article for creating a web api. Link

Happy Coding!!

Leave a Comment

%d bloggers like this: