0

我无法将其转换为 HTTPWebRequest。我使用 WebBrowser 让它完美地工作,但每当我尝试发出 HTTPWebRequest 时,它都会失败。我不确定我做错了什么。

工作代码:

private void Login()
{
    WebBrowser b = new WebBrowser();
    b.ScriptErrorsSuppressed = true;
    username = textBox1.Text;
    password = textBox2.Text;
    string PostData = string.Format("username={0}&password={1}&rk24={2}", username, password, rk24);
    ASCIIEncoding enc = new ASCIIEncoding();
    b.Navigate(url, "", enc.GetBytes(PostData), "Content-Type: application/x-www-form-urlencoded\r\n");
    b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}

private void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser b = sender as WebBrowser;
    string response = b.DocumentText;
    if (response.Contains("Sign out"))
    {
        this.Text = "LOGGED IN";
        b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
    }
    if (response.Contains("your info was incorrect"))
    {
        b.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
        this.Text = "LOGIN ERROR";
        MessageBox.Show("Invalid username or password!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

这是我对不起作用的 HTTPWebRequest 的尝试...

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    ASCIIEncoding enc = new ASCIIEncoding();
    string postData = string.Format("username={0}&password={1}&rk24={2}", user, pass, rk24);
    byte[] data = enc.GetBytes(postData);
    request.ContentLength = data.Length;
    Stream stream = request.GetRequestStream();
    stream.Write(data, 0, data.Length);
    stream.Close();
    WebResponse response = request.GetResponse();
    stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);
    string responseFromServer = reader.ReadToEnd();
    if(responseFromServer.Contains("Sign out"))
    {
        MessageBox.Show("Logged In!");
    }
    if (responseFromServer.Contains("your info was incorrect"))
    {
        MessageBox.Show("Invalid username or password");
    }
4

1 回答 1

0

登录系统大多使用 cookie 和会话来提供身份验证。Web 请求当然不会设置 cookie 等。这是浏览器的任务。这很可能是为什么 webbrowser 版本在处理 JS 并保存 cookie 时确实可以工作的原因。但是,您可以保存 cookie。看一下 CookieContainer 类。

我喜欢为这些情况扩展 WebClient 类。这是一个更抽象的版本,它在内部使用 webrequests 等。

也许这个片段会有所帮助:(也许打印cookie?如果这是问题,你一定要用浏览器检查这个)

 class MyWebClient : WebClient
{
    Uri _responseUri;
    public CookieContainer CookieContainer;

    public Uri ResponseUri
    {
        get { return _responseUri; }
    }

    public MyWebClient()
    {
        CookieContainer = new CookieContainer(); //TODO improve with read/write actions from disk. (binaryformatter)
    }

    public string GetCookieValue(string name)
    {
        return CookieContainer.GetCookies(_responseUri).Cast<Cookie>().First(c => c.Name == name).Value;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);

        var webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = CookieContainer;
        }

        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
        _responseUri = response?.ResponseUri;
        return response;
    }
}
于 2017-03-05T15:06:55.583 回答