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

后端 未结 8 1545
深忆病人
深忆病人 2020-11-22 07:12

I need to use \"HTTP Post\" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I wa

8条回答
  •  鱼传尺愫
    2020-11-22 08:05

    //Making a POST request using WebClient.
    Function()
    {    
      WebClient wc = new WebClient();
    
      var URI = new Uri("http://your_uri_goes_here");
    
      //If any encoding is needed.
      wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
      //Or any other encoding type.
    
      //If any key needed
    
      wc.Headers["KEY"] = "Your_Key_Goes_Here";
    
      wc.UploadStringCompleted += 
          new UploadStringCompletedEventHandler(wc_UploadStringCompleted);
    
      wc.UploadStringAsync(URI,"POST","Data_To_Be_sent");    
    }
    
    void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)    
    {  
      try            
      {          
         MessageBox.Show(e.Result); 
         //e.result fetches you the response against your POST request.         
      }
      catch(Exception exc)         
      {             
         MessageBox.Show(exc.ToString());            
      }
    }
    

提交回复
热议问题