多个帖子请求同一个会话c#

时间:2018-05-29 13:45:11

标签: c# post http-post httpwebrequest webrequest

我正在编写一个网站上的脚本,添加到购物车和结帐。 我设法添加到购物车,但当我想结帐时,它就像购物车中没有任何东西。 如何使用同一会话添加到购物车/结帐?

这是我的代码:

        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);

当我执行结帐请求时,它不起作用并获取网站html主页的源代码

非常感谢您的回答

1 个答案:

答案 0 :(得分:1)

您需要将request.CookieContainer存储在本地变量中,并且每次需要发送新请求时再次设置

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;
}

并将&添加到postData行的末尾