【问题标题】:C#: How to POST large string via WebRequest?C#:如何通过 WebRequest 发布大字符串?
【发布时间】:2011-02-15 08:30:15
【问题描述】:

如何使用 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;

【问题讨论】:

  • 应用程序的设计应使您不必发布大量数据。
  • 我对这个主题的看法是一样的。如果您发现“平台”不支持它,请尝试寻找另一种方法。否则我会选择@Marc Gravell 的方法,使用 gzip 压缩和有限的上传数量。

标签: c# httpwebrequest timeout http-post


【解决方案1】:

是的,这几乎是预期的 http 行为。

选项:

  • 有一个很大的超时时间(您已经这样做了),并接受可能需要很长时间才能合法地超时(而不是因为带宽而需要一段时间)
  • 也许您可以对请求应用 gzip(并告诉服务器您正在发送压缩文件);老实说,我不知道这是否受支持
  • 更改 api 以执行一些小上传,以及完成消息
  • 忍受它

【讨论】:

  • 不幸的是,WebService 只接受 XML 字符串。然后我必须使用很长的超时时间。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
相关资源
最近更新 更多