Post JSON data with Authorization header using asp.net and c#

Task: Post JSON data with Authorization header using asp.net and c#.

Description: Post JSON data with Authorization header using asp.net and c#. There is two methods for posting form, Get and Post. Here I used Post method with Basic Authorization header for submitting the form. 

using System.Net;
using System.IO;
using System.Web.Script.Serialization;
public class ProductResponse
{
    public string submitstatus { get; set; }
    public string reference { get; set; }

}
public void ProductSubmit( )
{
    try
    {
        string baseurl = "https://hemantrautela.blogspot.com/productsubmit";
        string Authkey = "ba1f3a6e97ceed3358c9b8a54d2a8f56efexy78d";
        string postString = @"{'productid': '7',
                          'quantity': '1',
                          'total_amount': 700.00,
                          'curruncy': 'INR',
                          'clientIpAddress': '" + Request.UserHostAddress + @"',
                          'clientUserAgent': '" + Request.UserAgent + @"' }";


        HttpWebRequest webReq = WebRequest.Create(baseurl) as HttpWebRequest;
        webReq.Method = "POST";
        webReq.ContentType = "application/json; charset=utf-8";
        webReq.ContentLength = postString.Length;
        webReq.Accept = "application/json";
        webReq.Headers.Add("API-Version", "4.1.0");


        byte[] authBytes = Encoding.UTF8.GetBytes((Authkey).ToCharArray());
        webReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(authBytes));

        StreamWriter requestWriter = new StreamWriter(webReq.GetRequestStream());
        requestWriter.Write(postString);
        requestWriter.Close();

        StreamReader responseReader = new StreamReader(webReq.GetResponse().GetResponseStream());

        string responseData = responseReader.ReadToEnd();

        ProductResponse productresp = new JavaScriptSerializer().Deserialize<ProductResponse>(responseData);

        List<ProductResponse> resp_obj = new List<ProductResponse>();
        resp_obj.Add(productresp);

        string referencevalue = productresp.reference;
        string submitstatus = productresp.submitstatus;

        responseReader.Close();
        webReq.GetResponse().Close();
    }
    catch (Exception ex)
    {
    }
}
 

2 comments:

  1. Thanks for your informative blog!!! Your article helped me to understand the future of .net programming language. Keep on updating your with such awesome information. DOT NET Training in Chennai | dot net course Chennai

    ReplyDelete
  2. Dot Net is an ever trending technology where it is more preferable by developers to utilize the features in the dot net language. your article on Dot Net language proves that it is an evergreen technology in the IT market.

    DOT NET Course in T Nagar |
    Dot Net Training in Tambaram

    ReplyDelete