我无法使用WebClient在网站上添加自动处理

时间:2018-11-13 07:41:11

标签: c# http-post httpclient webclient

我有一个问题。我应该在网站上添加自动处理,然后进行解析。

我使用webBrowser解决了该问题,但我想使用webClient或HttpClient完成

HTML代码

<form role="form" method="POST">
    <div class="form-row">
        <input type="text" id="userLogin" required="required"
                            name="username" placeholder="Username" autofocus="autofocus">
    </div>
    <div class="form-row">
        <input type="password" id="userPassword" required="required" 
                            name="password" placeholder="Password">
    </div>
<div class="btns-row">
                <span class="forgot-pwd"><a href="/app/recoverPassword/">Forget password?</a></span>
                <button id="userSignIn" class="btn" type="submit">Enter</button>
            </div>
        </div>
        <input type="hidden" id="urlParams" name="params" />
    </form>

我试图这样做,但是没有用

private void button3_Click(object sender, EventArgs e)
{

    using (var webClient = new CookieAwareWebClient())
    {
        //webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
        webClient.UploadString("http://server/app/login/", "username=user1&password=pass1");
        //webClient.Headers.Remove(HttpRequestHeader.ContentType);

        string answer = webClient.DownloadString("http://server/app/obj/");
        richTextBox1.AppendText(answer);

    }



}

Cookie类

public class CookieAwareWebClient : WebClient
{
    public void Login(string loginPageAddress, NameValueCollection loginData)
    {
        CookieContainer container;

        var request = (HttpWebRequest)WebRequest.Create(loginPageAddress);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        var query = string.Join("&",
          loginData.Cast<string>().Select(key => $"{key}={loginData[key]}"));

        var buffer = Encoding.ASCII.GetBytes(query);
        request.ContentLength = buffer.Length;
        var requestStream = request.GetRequestStream();
        requestStream.Write(buffer, 0, buffer.Length);
        requestStream.Close();

        container = request.CookieContainer = new CookieContainer();

        var response = request.GetResponse();
        response.Close();
        CookieContainer = container;
    }

    public CookieAwareWebClient(CookieContainer container)
    {
        CookieContainer = container;
    }

    public CookieAwareWebClient()
      : this(new CookieContainer())
    { }

    public CookieContainer CookieContainer { get; private set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = CookieContainer;
        return request;
    }
}

您能帮我如何使用webClient或HttpClient在网站上进行自动审核吗?

0 个答案:

没有答案