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 is one of the easiest ways 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;

WebClient downloads files. Found in the System.Net namespace, it downloads web pages and files. WebClient is powerful. It is versatile. This class makes it possible to easily download web pages for testing.

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. Below is a simple implementation of using WebClient GET request.

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

Method: POST

Uploads the specified string to the specified resource, using the POST method.

public string UploadString (string address, string? method, string data);

Sample Code:

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, "POST", 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. You may also visit HTTPClient Request in .NET Framework.

Keep Coding!!