POST后登录(登录)

时间:2015-01-16 16:32:34

标签: c# http

我有一个网站,我每天检查我的产品清单。我想为它制作一个桌面程序。

我需要首先登录网站然后转到site.com/v1/ProductList这是一个xml文档。我已设法使用此代码登录:

            CookieCollection cookies = new CookieCollection();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FirstURL);
        request.CookieContainer = new CookieContainer();
        request.CookieContainer.Add(cookies);
        //Get the response from the server and save the cookies from the first request..
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        cookies = response.Cookies;
        string postData = "Username=x&Password=x&List=1&Submit=Submit";
        HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
        getRequest.CookieContainer = new CookieContainer();
        getRequest.CookieContainer.Add(cookies); //recover cookies First request
        getRequest.Method = WebRequestMethods.Http.Post;
        getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
        getRequest.AllowWriteStreamBuffering = true;
        getRequest.ProtocolVersion = HttpVersion.Version11;
        getRequest.AllowAutoRedirect = true;
        getRequest.ContentType = "application/x-www-form-urlencoded";

        byte[] byteArray = Encoding.ASCII.GetBytes(postData);
        getRequest.ContentLength = byteArray.Length;
        Stream newStream = getRequest.GetRequestStream(); //open connection
        newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
        newStream.Close();

        HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            string sourceCode = sr.ReadToEnd();
        }

我在这里成功登录。 但在此之后,如果我为我的列表(site.com/v1/ProductList)创建一个新的get请求并获取请求,它会将我重定向到登录页面。

编辑:我刚刚意识到我登录后无法获得任何cookie。它说"'枚举没有产生任何结果'"。

我现在不知道如何修复它。

由于

1 个答案:

答案 0 :(得分:0)

更改此行:

getRequest.AllowAutoRedirect = true;

到此:

getRequest.AllowAutoRedirect = false;

确保您实际将其设置为false并且不要删除该行,因为默认情况下,它会设置为true