我如何使用 POST 上传大字符串(在我的例子中是带有 BLOB 的 XML)而不用 GetResponse 超时?
更改超时会有所帮助,但这并不是真正的解决方案。 如果服务器真的死机或 POST 被中断,我必须等待极长的超时时间。
有什么想法吗?
HttpWebRequest webRequest = null;
string response = "";
byte[] bytes = Encoding.UTF8.GetBytes(xml);
try
{
webRequest = (HttpWebRequest)WebRequest.Create("http://" + this.host + ":" + this.port);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
webRequest.Timeout = 5000;
webRequest.ContentLength = bytes.Length;
using (Stream requeststream = webRequest.GetRequestStream())
{
requeststream.Write(bytes, 0, bytes.Length);
requeststream.Close();
}
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
{
response = sr.ReadToEnd().Trim();
sr.Close();
}
webResponse.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
return response;
最佳答案
是的,这几乎是预期的 http 行为。
选项:
- 有很长的超时时间(你已经这样做了),并接受可能需要很长时间才能合法地超时(而不是因为带宽而需要一段时间)
- 也许您可以对请求应用 gzip(并告诉服务器您发送的是压缩文件);老实说,我不知道这是否受自动支持,但它肯定可以通过 api 显式检查特定 header 并对有效负载应用 gzip 解压缩来完成
- 更改 api 以执行一些小的上传和完成消息
- 接受它
关于C#:如何通过 WebRequest 发布大字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5001314/