Friday, September 16, 2016

HttpWebRequest cookie post header Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using System.Diagnostics;

namespace HttpWebRequestExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        CookieContainer Cookie = null;
        string CSRFtoken = "";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void LoginBtn_Click(object sender, RoutedEventArgs e)
        {
            Cookie = new CookieContainer(); // important

            PerformRequest("POST", "https://erp.local:8443/Login", "{\"ObjArr\":[{\"Username\":\"bot\",\"Password\":\"bot\"}]}");
        }

        private void ItemBtn_Click(object sender, RoutedEventArgs e)
        {
            PerformRequest("GET", "https://erp.local:8443/Item/List", "");
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            PerformRequest("POST", "https://erp.local:8443/Ship/Save", "{\"Status\":true,\"ErrArr\":[],\"ErrCount\":0,\"ObjArr\":[{\"IDCNShip\":0,\"InvoiceNum\":15,\"ContainerNum\":\"\",\"ETD\":\"2016-09-13\",\"ETA\":\"\",\"IDWarehouse\":0,\"TotalQty\":0,\"IsClosed\":false,\"ShippedDate\":\"\",\"Remark\":\"\",\"Created\":\"\",\"Changed\":\"\",\"CNShipItemWalkerArr\":[{\"LineNum\":0,\"RowNum\":1,\"ItemNum\":\"A0\",\"ItemName\":\"\",\"SizeLong\":\"\",\"ColorShort\":\"\",\"ColorShortZH\":\"\",\"Qty\":0,\"NetWeight\":0,\"GrossWeight\":0,\"UnitPrice\":0,\"Remark\":\"\",\"Created\":\"\",\"Changed\":\"\"}],\"CNShipItemPartArr\":[{\"LineNum\":0,\"BoxLabel\":\"ABC\",\"ItemNum\":\"A1\"}]}],\"Data\":{}}");
        }

        private void PerformRequest(string method, string url, string postData)
        {
            // TODO: this is a temporary remove SSL ceritficate check solution. Please comment out this line in production.
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = Cookie; // use the global cookie variable


            byte[] data = Encoding.UTF8.GetBytes(postData);

            request.Method = method;

            request.Headers.Add("X-CSRF-Token", CSRFtoken);

            if (method == "POST")
            {
                request.ContentType = "application/json; charset=utf-8";
                request.ContentLength = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            WebResponse response = (HttpWebResponse)request.GetResponse();
            string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            CSRFtoken = response.Headers.Get("X-CSRF-Token");

            Debug.WriteLine("CSRFtoken: " + CSRFtoken);
            Debug.WriteLine(responseString);
        }

        public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}


Reference:

http://csharp-tricks-en.blogspot.ca/2015/03/http-requests-get-or-post-with-cookies.html

No comments: