Sunday, March 15, 2015

HTTP Requests (GET or POST) with Cookies in C#

On the internet I found many explanations on how to use cookies in C# for HTTP GET or POST requests, but these were mostly long and complicated. Therefor I want to present a method here, which is the easiest in my opinion: With only 2 lines of code we can save / use cookies and this way for example use and keep PHP sessions.
For this we use the class HttpWebRequest, which was introduced in a previous post. It contains a property CookieContainer, in which we can save cookies or read them from it. If we use a webservice, which uses cookies, for the first time during the request a cookie is created and saved in the CookieContainer. Then we simply save this to a global variable and set this as CookieContainer on the next request. This way, the cookie is reused and the webservice remembers us.
In the following example the PHP example regarding sessions from the previous post is used. The PHP script is called two times, because of the usage of cookies it recognizes our second visit:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net;
using System.IO;

namespace PHPPost
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        CookieContainer Cookie = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            Cookie = new CookieContainer(); // important
            PerformRequest();
            PerformRequest();
        }

        private void PerformRequest()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://bloggeroliver.bplaced.net/PHPExamples/session.php");
            request.CookieContainer = Cookie; // use the global cookie variable
            string postData = "";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; 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();
        }
    }
}

If we omit the 2. line with the CookieContainer in the function PerformRequest(), the script naturally does not recognize us. Further important is the line Cookie = new CookieContainer(); for initialization, because otherwise the container cannot be used.

No comments:

Post a Comment