1

目前我正在尝试使用 c# 代码(HttpWebRequest/HttpWebResponse)模拟登录,但是我最终得到了 login.aspx 网页的 html 文本,而不是成功登录后的 html 文本。返回的变量“html”与 login.aspx 网页本身完全相同,似乎根本没有发布数据。请帮忙。谢谢你。戴夫。这是我使用的代码

var LOGIN_URL = "http://altech.com.au/login.aspx";

HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream());
string responseData = responseReader.ReadToEnd();
responseReader.Close();

string postData =String.Format(
 "ctl00$ContentPlaceHolderBodyMain$txtEmail {0}&ctl00$ContentPlaceHolderBodyMain$txtPassword={1}&btnLogin=Login","myemail", "mypassword");

//have a cookie container ready to receive the forms auth cookie
CookieContainer cookies = new CookieContainer();

// now post to the login form
webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";

// write the form values into the request message
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postData);
requestWriter.Close();

HttpWebResponse response2 = (HttpWebResponse)webRequest.GetResponse();
StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.Default);
string html = sr2.ReadToEnd(); 
4

1 回答 1

1

您需要对数据进行 URL 编码,否则将不被接受。

Dictionary<string, string> FormData = new Dictionary<string, string>();

//Add all of your name/value pairs to the dictionary
FormData.Add(
    "ctl00$ScriptManager1",
    "ctl00$ContentPlaceHolderBodyMain...");

...然后正确格式化...

public string GetUrlEncodedPostData(
    Dictionary<string, string> FormData)
{
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < FormData.Count(); ++i)
    {
        //Better to use string.join, but this is a bit more clear ^_^
        builder.AppendFormat(
            "{0}={1}&",
            WebUtility.UrlEncode(InputNameValue.ElementAt(i).Key),
            WebUtility.UrlEncode(InputNameValue.ElementAt(i).Value));
    }

    //Remove trailing &
    builder.Remove(builder.Length - 1, 1);

    return builder.ToString();
}
于 2013-03-29T23:12:07.583 回答