tags:

views:

87

answers:

1

i want to post the form with defined data, but it fails. If login success, the CookieContainer should contain a "username" field. I have used FireBug + firefCookie to browse the responsed cookie,it haven't that. And browse the responsed HTML, it don't say i am login incorrect..

one more thing i conside is the field name of post data, i should use the id or name ?

<input name="ctl00$ContentPlaceHolder1$txt_email" type="text" size="15" id="ctl00_ContentPlaceHolder1_txt_email" /> <input name="ctl00$ContentPlaceHolder1$txt_pass" type="password" maxlength="8" size="15" id="ctl00_ContentPlaceHolder1_txt_pass" /> <input id="ctl00_ContentPlaceHolder1_cb_remember_login" type="checkbox" name="ctl00$ContentPlaceHolder1$cb_remember_login" checked="checked" />

Below is the code ,

        string LoginUrl = "http://forum5.hkgolden.com/login.aspx";

        HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(LoginUrl);
        CookieContainer cookiecontainer  = new CookieContainer();
        request.CookieContainer = cookiecontainer;
        request.Method = WebRequestMethods.Http.Post;
        request.ContentType = "application/x-www-form-urlencoded";

        string PostData = Uri.EscapeDataString("[email protected]&txt_pass=mypassword&cb_remember_login=on");

        Byte[] PostBuffer = Encoding.GetEncoding("BIG5").GetBytes(PostData);
        request.ContentLength = PostBuffer.Length;
        Stream PostStream = request.GetRequestStream();
        PostStream.Write(PostBuffer, 0, PostBuffer.Length);
        PostStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        cookiecontainer.Add(new Uri("http://www.hkgolden.com"), response.Cookies); //Add CookiesCollection to Container

        Encoding enc = Encoding.GetEncoding("BIG5");
        StreamReader ResponseStream = new StreamReader(response.GetResponseStream(), enc);
        string strHtml = ResponseStream.ReadToEnd();
        response.Close();
        ResponseStream.Close();

        System.Diagnostics.Debug.Print(strHtml);
A: 

For the first issue, it may be caused by your http request doesn't contain sufficient data. If you log in through the web browser and capture http traffic, you'll notice there are huge difference between the data posted by your application and the browser. Try to add those missing fields in your code.

When you submit a html form, the default behavior is all elements with name attribute inside the form will be posted to server. The format of posted data is Element1_Name=Element1_value&Element2_Name=Element2_value . So name is the correct attribute to use.

Raymond