How to make HTTP POST web request using C#



In order to send data through the HTTP POST WebRequest class, you need to go through the following step-by-step procedure. Usually, this procedure is used to submit data to a Web page

To submit data to a host server, create a WebRequest application by calling WebRequest.Create with the URL (starting with ftp:, http:, https:, and file) of a resource like an ASP.NET page that receives data.

var httpWebRequest = (HttpWebRequest)WebRequest.Create({URL});

Mention a protocol method like the HTTP POST/GET/PUT/DELETE method that allows data to be transferred with a request.

Mention a Content-Type application/json but you can change it according to your content type.

Mention an Accept application/json but you can change it according to your Accept.

httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Accept = "application/json";

Full Example of Post API 

In this example, need to pass API URL and JSON Data.

 public string PostAPI(string api, string data)
        {
            string sResponseFromServer = string.Empty;
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(api);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Accept = "application/json";
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    sResponseFromServer = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                sResponseFromServer = ex.Message.ToString();
            }
            return sResponseFromServer;
        }

0 Comment's

Comment Form