发送大文件/内容时 HttpClient 是否有缺陷?

sap*_*ito 5 c# .net-4.5

在阅读/谷歌搜索 HttpClient 后,我​​的印象是该组件不适合将大文件或内容上传到 REST 服务。

  1. 似乎如果上传时间超过既定的超时时间,传输就会失败。是否有意义?这个超时是什么意思?

  2. 获取进度信息似乎很难或需要附加组件。

所以我的问题是:是否有可能在没有太多麻烦的情况下解决这两个问题?否则,处理大型内容和 REST 服务时的最佳方法是什么?

Boi*_*nst 4

  1. 是的,如果上传时间超过 TimeOut,上传将会失败。这是 的限制HttpClient。这个问题最强大的解决方案是Thomas Levesque了一篇关于 的文章,并在他的评论中链接到您的问题。你必须使用HttpWebRequest而不是HttpClient.
  2. 如果您想获取进度消息,请以 a 形式打开文件FileStream并手动迭代它,将字节增量复制到(上传)请求流上。当您进行操作时,您可以计算相对于文件大小的进度。

TL的代码示例。不过一定要阅读这篇文章!

long UploadFile(string path, string url, string contentType)
{
    // Build request
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = WebRequestMethods.Http.Post;
    request.AllowWriteStreamBuffering = false;
    request.ContentType = contentType;
    string fileName = Path.GetFileName(path);
    request.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", fileName);

    try
    {
        // Open source file
        using (var fileStream = File.OpenRead(path))
        {
            // Set content length based on source file length
            request.ContentLength = fileStream.Length;

            // Get the request stream with the default timeout
            using (var requestStream = request.GetRequestStreamWithTimeout())
            {
                // Upload the file with no timeout
                fileStream.CopyTo(requestStream);
            }
        }

        // Get response with the default timeout, and parse the response body
        using (var response = request.GetResponseWithTimeout())
        using (var responseStream = response.GetResponseStream())
        using (var reader = new StreamReader(responseStream))
        {
            string json = reader.ReadToEnd();
            var j = JObject.Parse(json);
            return j.Value<long>("Id");
        }
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.Timeout)
        {
            LogError(ex, "Timeout while uploading '{0}'", fileName);
        }
        else
        {
            LogError(ex, "Error while uploading '{0}'", fileName);
        }
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)