简体   繁体   中英

multiple post requests same session c#

I'm coding a script that goes on a website, adds to cart an item, and checkout. I manage to add to cart but when I want to checkout it's like nothing is in the cart. How can I add to cart/ checkout using the same session?

Here is my code:

        var request = (HttpWebRequest)WebRequest.Create(url_add_to_cart);

        var postData = "utf8=✓";
        postData += "style=" + data_style_id;
        postData += "size=" + size;
        postData += "commit=add to basket";
        var data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        var response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        //checkout----------------
        var url_checkout = link_general + "/checkout.json";
        var request2 = (HttpWebRequest)WebRequest.Create(url_checkout);

        var postData2 = "utf8=✓";
        postData2 += "order[billing_name]=toto";
        postData2 += "order[email]=toto@gmail.com";

        var data2 = Encoding.ASCII.GetBytes(postData2);

        request2.Method = "POST";
        request2.ContentType = "application/x-www-form-urlencoded";
        request2.ContentLength = data2.Length;

        using (var stream2 = request2.GetRequestStream())
        {
            stream2.Write(data2, 0, data2.Length);
        }

        var response2 = (HttpWebResponse)request2.GetResponse();

        var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();


        Console.WriteLine(responseString2);

When I do the checkout request it doesn't work and get the source corde of the website html home page

Thank you very much for your answers

You need to store request.CookieContainer in local variable and every time you need to send new request set it again

private CookieContainer cookieContainer;

private void SendRequest()
{
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
    request.ContentType = "application/x-www-form-urlencoded";
    request.Method = "POST";

    if (this.cookieContainer != null)                
        request.CookieContainer = this.cookieContainer;                
    else                
        request.CookieContainer = new CookieContainer();                
    ...
    ...
    ...

    this.cookieContainer = request.CookieContainer;
}

And add & to end of postData lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM