1

我试图在同一个会话上做 2 个发布请求,但第二个总是给我主页的 html 源代码......

这两个函数的作用完全相同:发出一个 post 请求并将其添加到 cookie 容器中。在第二个函数结束时,响应字符串向我发送了主页的 html 源页面,而不是我之前的那个。而第一个帖子请求中的响应字符串(当我之前尝试过时)向我发送了良好的 html 源页面。

这是我的代码:

private CookieContainer cookieContainer;

private void SendRequest_add_to_cart(string url, string data_style_id, string size)
{
    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();

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

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

    this.cookieContainer = request.CookieContainer;
}

private void SendRequest_checkout(string url)
{
    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();

    var postData = "utf8=✓";
    postData += "order[billing_name]=toto";
    postData += "order[email]=toto@gmail.com";
    var data = Encoding.ASCII.GetBytes(postData);

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

    this.cookieContainer = request.CookieContainer;
    Console.WriteLine(responseString);
}

这是我之前启动的功能:

var url_add_to_cart = link_general + doc.DocumentNode.SelectSingleNode("//form").Attributes["action"].Value;
var url_checkout = link_general + "/checkout.json";

    SendRequest_add_to_cart(url_add_to_cart, data_style_id, size);
    SendRequest_checkout(url_checkout);

如果有人有想法可以帮助我,那就太好了!非常感谢!

4

1 回答 1

0

感谢@Hesam Fraridmehr,这是答案:

添加: & 到这样的行: -postData += "&style=" + data_style_id;

希望它可以帮助别人

于 2018-05-29T19:27:22.253 回答