How to call/Consume post API with Header in C#



This is simple sample code written to consume post API which has header  


Here I am using newtonsoft dll to convert class into json

    //using Newtonsoft.Json
    private void PostWithHeader()
    {

        WebRequest req = null;
        WebResponse rsp = null;
        string url = "http://"; // Pass url here
        string API_Response = "";
        jsonParameter P = new jsonParameter() { userid=1};

        try
        {
            req = WebRequest.Create(url);
            //Uncomment below line if Post with Basic auth also pass username & passord
            // req.Headers.Add(HttpRequestHeader.Authorization "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("userName:password")));

            //Uncomment below line If you want pass header key & their value also change key name & value           
            //req.Headers.Add("accesskey", "ccc"); //Key & Value

            req.Method = "post";
            req.ContentType = "application/json; charset=UTF-8";// "application/json"; //x-www-form-urlencoded";
            StreamWriter writer = new StreamWriter(req.GetRequestStream());
            writer.Write(JsonConvert.SerializeObject(P)); // Pass parameter as class
            writer.Close();

            // Send the data to the webserver
            rsp = req.GetResponse();

            StreamReader reader = new StreamReader(rsp.GetResponseStream());
            API_Response = reader.ReadToEnd();
            //return JsonConvert.DeserializeObject(API_Response);
            //return API_Response;
            Response.Write(API_Response);
        }
        catch (Exception ex)
        {
        }


    }
    public class jsonParameter
    {
        public int userid { get; set; }
    }

Comments

Popular posts from this blog

Multipart/form-data using basic auth

How to Capture image of HTML5 camera in asp.net

Simple API that receive MultipartData File with parameter in ASP.net Web API