How to post data to specific URL using WebClient in C#?

CsharpServer Side ProgrammingProgramming

We can Get and Post data from a Web API using Web client. Web client provides common methods for sending and receiving data from Server

Web client is easy to use for consuming the Web API. You can also use httpClient instead of WebClient

The WebClient class uses the WebRequest class to provide access to resources.

WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.

Namespace:System.Net
Assembly:System.Net.WebClient.dll

UploadString Sends a String to the resource and returns a String containing any response.

Example

class Program{
   public static void Main(){
      User user = new User();
      try{
         using (WebClient webClient = new WebClient()){
            webClient.BaseAddress = "https://jsonplaceholder.typicode.com";
            var url = "/posts";
            webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            webClient.Headers[HttpRequestHeader.ContentType] ="application/json";
            string data = JsonConvert.SerializeObject(user);
            var response = webClient.UploadString(url, data);
            var result = JsonConvert.DeserializeObject<object>(response);
            System.Console.WriteLine(result);
         }
      }
      catch (Exception ex){
         throw ex;
      }
   }
}
class User{
   public int id { get; set; } = 1;
   public string title { get; set; } = "First Data";
   public string body { get; set; } = "First Body";
   public int userId { get; set; } = 222;
}

Output

{
   "id": 101,
   "title": "First Data",
   "body": "First Body",
   "userId": 222
}
raja
Published on 25-Sep-2020 11:15:09
Advertisements