[英]HttpWebRequest .GetResponse throws WebException 'The operation has timed out'
[英]HttpWebRequest upload file cause The operation has timed out WebException
我一直在寻找答案,但真的不知道是什么导致了我的问题。 我正在使用 HttpWebRequest 将文件上传到我的服务器,该方案应该是正确的:
1. 组合多部分表单数据、边界和尾部。
2. 结合表单数据、文件的长度来设置请求的内容长度。
3.直接写入流并跟踪上传进度。
这是我正在使用的代码:
HttpWebRequest uploadWebRequest = Func.UploadFileCompose(string.Format("url?hash={0}", uploadKeys.hash), cookieCollection);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "video", Path.GetFileName(videoModel.DownloadedLocation), "video/mp4");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + Func.boundary + "--\r\n");
long totalBytes = 0;
using(FileStream fileStream = new FileStream(videoModel.DownloadedLocation,FileMode.Open, FileAccess.Read))
{
totalBytes += headerbytes.Length;
totalBytes += fileStream.Length;
totalBytes += trailer.Length;
}
uploadWebRequest.ContentLength = totalBytes;
using (Stream requestStream = uploadWebRequest.GetRequestStream())
{
requestStream.ReadTimeout = 10000;
requestStream.WriteTimeout = 10000;
//write header first
requestStream.Write(headerbytes, 0, headerbytes.Length);
using (FileStream fileStream = new FileStream(videoModel.DownloadedLocation, FileMode.Open, FileAccess.Read))
{
int bytesRead = 0;
long bytesSent = 0;
byte[] buffer = new byte[1024000];
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
bytesSent += bytesRead;
requestStream.Write(buffer, 0, bytesRead);
decimal percentage = (decimal)(bytesSent * 100) / (decimal)fileStream.Length;
if (Math.Round(percentage, 1) % 0.2M == 0)
{
Func.SetProgressStatus(lvStatus, "Uploaded: " + Math.Round(percentage, 1) + "%");
}
}
}
//write trailer
requestStream.Write(trailer, 0, trailer.Length);
}
string uploadResponseInStr = "";
using (HttpWebResponse response = (HttpWebResponse)uploadWebRequest.GetResponse())
{
var encoding = ASCIIEncoding.ASCII;
try
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
uploadResponseInStr = await reader.ReadToEndAsync();
}
}
catch (Exception e1)
{
return null;
}
}
试图设置
req.KeepAlive = true; //true or false
req.Timeout = 10000;
req.ReadWriteTimeout = 10000;
req.ProtocolVersion = HttpVersion.Version10; // 11 or 10
没有帮助。
提前感谢您的帮助。 真的很感激!
编辑:设置 DefaultConnectionLimit 等于 1000 没有帮助。
连接已建立,但在引发异常之前只上传了几 MB
解决了。!
此请求缺少边界且长度不正确。
也有必要将边界写入流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.