WebClient UploadValuesTaskAsync

末鹿安然 提交于 2019-12-13 02:14:47

问题


Here is my WebClient class:

class MyWebClient : WebClient
{
    private CookieContainer _cookieContainer = new CookieContainer();
    public MyWebClient(string url, string login, string password)
    {
        var data = new NameValueCollection
            {
                { "username",  login},
                { "password",  password}
            };
       UploadValues(new Uri(url), data);
    }
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = _cookieContainer;
        }
        return request;
    }
}

And here is sample, how i want to use it:

private MyWebClient _client;

private void btnLogin_Click(object sender, RoutedEventArgs e)
{
     _client = new MyWebClient("http://website/login.php", "account", "pw");
}

private async void btnContent_Click(object sender, RoutedEventArgs e)
{
     _client = await _client.DownloadStringTaskAsync("http://website");
}

And my question is.. With this MyWebClient class, how can i login async? I hope someone will be able to help me, thank you!


回答1:


You can move the login logic outside the constructor and use the UploadValuesTaskAsync method like this:

class MyWebClient : WebClient
{
    //...
    private readonly string m_Uri;
    private readonly string m_Login;
    private readonly string m_Password;

    public MyWebClient(string url, string login, string password)
    {
        m_Password = password;
        m_Login = login;
        m_Uri = url;
    }

    public async Task LogIn()
    {
        var data = new NameValueCollection
        {
            {"username", m_Login},
            {"password", m_Password}
        };
        await UploadValuesTaskAsync(new Uri(m_Uri), data);
    }

    //...
}

And then use it like this:

private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
     _client = new MyWebClient("http://website/login.php", "account", "pw");
     await _client.LogIn();
}


来源:https://stackoverflow.com/questions/34977589/webclient-uploadvaluestaskasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!