httpwebrequest,httpwebresponse不太合适

时间:2011-12-10 18:43:41

标签: c# asp.net cookies httpwebrequest httpwebresponse

我有一个Windows窗体应用程序,用于登录网站并检索网页的内容(html代码)。

我从Windows窗体应用程序更改代码,使其与.aspx页面一起使用,但我遇到了问题。在下面的字符串(页面)中没有任何内容保存:

private void button1_Click(object sender, EventArgs e)
        {
            string postData = "bla bla bla...";
            CookieContainer tempCookies = new CookieContainer();
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteData = encoding.GetBytes(postData);

        HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("http://bla bla bla...php");
        postReq.Method = "POST";
        postReq.KeepAlive = true;
        postReq.CookieContainer = tempCookies;
        postReq.ContentType = "application/x-www-form-urlencoded";
        postReq.Referer = "http://bla bla bla...php";
        postReq.UserAgent = "Opera/9.80 (Windows NT 6.1; U; en-GB) Presto/2.9.168 Version/11.52";
        postReq.ContentLength = byteData.Length;

        Stream postreqstream = postReq.GetRequestStream();
        postreqstream.Write(byteData, 0, byteData.Length);
        postreqstream.Close();
        HttpWebResponse postresponse = default(HttpWebResponse);

        postresponse = (HttpWebResponse)postReq.GetResponse();
        tempCookies.Add(postresponse.Cookies);
        logincookie = tempCookies;
        StreamReader postreqreader = new StreamReader(postresponse.GetResponseStream());

        string thepage = postreqreader.ReadToEnd();
        TextBox1.Text = thepage;

表单应用程序工作正常,但.aspx没有。不知道为什么。拜托,帮助我。感谢。

1 个答案:

答案 0 :(得分:1)

在黑暗中拍摄,在这里,但尝试

postReq.Credentials = CredentialCache.DefaultCredentials;

如果不这样做,您可以随时打开Fiddler或FireBug来查看来回发送的请求和响应。也许您会看到您发送的数据与请求不符合您的期望?