Tomo84
Tomo84

Reputation: 21

httpwebrequest, httpwebresponse not quite working

I have a windows form application which serves to login to a website and retrieve the content (html code) of a webpage.

I change my code from windows form application to make it work with an .aspx page, but I have problems. Nothing gets saved in the string (thepage) below:

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;

The form application works fine, but the .aspx does not. Have no idea why. Please, help me with that. Thanks.

Upvotes: 1

Views: 303

Answers (1)

hawkke
hawkke

Reputation: 4262

Shot in the dark, here, but try

postReq.Credentials = CredentialCache.DefaultCredentials;

Failing that, you could always open up Fiddler or FireBug to see the request and response being sent back and forth. Maybe you'll see that the data you are sending along with the request isn't what you expect it to be?

Upvotes: 1

Related Questions