如何将此webbrowser请求更改为HTTPWebRequest?

时间:2013-10-19 18:27:10

标签: c# winforms httpwebrequest webrequest

我无法将其转换为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");
    }

1 个答案:

答案 0 :(得分:0)

登录系统主要使用cookie和会话来提供身份验证。 Webrequests docourse不设置cookie等。这是浏览器的任务。 这很可能是为什么webbrowser verion确实有效,因为这会处理JS并保存cookie以及所有这些。 但是你可以保存cookie。看一下CookieContainer类。

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

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

 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;
    }
}