Webclient + UploadStringAsync +事件:UploadProgressChanged / DownloadProgressChanged

时间:2019-04-05 18:12:44

标签: c# .net rest httpwebrequest webclient

我需要与REST服务进行通信。

由于某些原因,我必须使用 POST 请求从该服务获取JSON数据。 (我认为它应该使用GET请求,但这不在我的控制之下,我无法更改...)

一个请求的响应大约为25-30 MB。 由于响应很大,因此我决定使用WebClient和UploadStringAsync方法。

private string jsonResult = "";

void test()
{
    string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + passowrd));  
    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
        client.UploadProgressChanged += new UploadProgressChangedEventHandler(client_UploadProgressHandler);
        client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompletedHandler);                
        client.Headers.Add("Authorization", "Basic " + credentials);
        client.Encoding = System.Text.Encoding.UTF8;
        Uri uri = new Uri(https://demoapi.org/stuff/prod/0);

        client.UploadStringAsync(uri, "POST", "");
    }
}

private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("DOWNLOAD_PROGRESS!");
    Console.WriteLine("Status {0} of {1} bytes. {2} % complete", e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage);
}

private static void client_UploadProgressHandler(object sender, UploadProgressChangedEventArgs e)
{
    Console.WriteLine("UPLOAD_PROGRESS!");
    Console.WriteLine("Status {0} of {1} bytes. {2} % complete, {3} of {4} bytes. {5} % complete", e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage, e.BytesSent, e.TotalBytesToSend, e.ProgressPercentage);
}

private void client_UploadStringCompletedHandler(Object sender, UploadStringCompletedEventArgs e)
{
    Console.WriteLine("UPLOAD_COMPLETED!");
    jsonResult = e.Result;
}

使用上面的代码,控制台多次显示消息UPLOAD_PROGRESS!然后出现消息UPLOAD_COMPLETED!但是,我没有看到消息DOWNLOAD_PROGRESS!

UPLOAD_PROGRESS!
UPLOAD_PROGRESS!
....    
UPLOAD_PROGRESS!
UPLOAD_COMPLETED!

这是我的问题:

1)我可以(确实)使用webclient.UploadStringAsync方法订阅“ UploadProgressChanged”事件吗?

Microsoft文档没有说UploadProgressChanged可用于UploadStringAsync,但无论如何似乎与上面的代码一起使用。

https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadprogresschanged?view=netframework-4.7.2

https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstringasync?view=netframework-4.7.2

我也查看了Microsoft参考资料,但我并不完全理解。 委托'UploadProgressChanged'似乎没有出现在UploadStringAsync方法中。

https://referencesource.microsoft.com/#System/net/System/Net/webclient.cs,d15a560fedc713da,references

因此,我想知道将webclient.UploadStringAsync与“ UploadProgressChanged”一起使用是否正确。

2)我可以使用webclient.UploadStringAsync方法订阅“ DownloadProgressChanged”事件吗?

3)据我了解,Web客户端在后台使用WebRequest和WebResponse。是否可以同时获得两个请求的进度?

我之所以这样问,是因为有时请求的内容很大,有时响应很大。

4)如果DownloadProgressChangedEvent不可用,则 如何报告“ UploadStringAsync” POST请求的WebResponse部分的进度?

谢谢

1 个答案:

答案 0 :(得分:1)

您上面的代码执行上载,因此它无法接收到DownloadProgressChanged事件。

规则是所有Download或Upload Async方法都会引发相应的Download或Upload进度更改事件。在场景下,UploadStringAsync使用的是与UploadDataAsync使用的相同的代码(因为字符串是按字符编码取模的字节数组)。

非异步方法不会引发进度事件。

如果要访问基础WebRequest,只需创建一个从WebClient派生并覆盖protected virtual GetWebRequest(Uri address)方法的类,如下所示:

public class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        // do something with the request
        // BTW, this is how you can change timeouts or use cookies
        return request;
    }
}

请注意,您也可以使用更现代的HttpClient类(完全跨平台,框架等)代替WebClient。