C#:如何通过WebRequest发布大字符串?

Wow*_*owa 9 c# timeout http-post httpwebrequest

我如何使用POST上传一个大字符串(在我的情况下使用BLOB的XML)而不使用GetResponse获取Timeout?

更改超时有帮助,但这不是一个真正的解决方案.如果服务器确实死亡或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;
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 3

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

选项:

  • 有一个很大的超时(您已经这样做了),并接受可能需要很长时间才能合法超时(而不是因为带宽而花费一段时间)
  • 也许您可以对请求应用 gzip (并告诉服务器您正在以压缩的方式发送它);老实说,我不知道这是否是自动支持的,但它肯定可以通过 api 显式检查特定标头并对有效负载应用 gzip 解压缩来完成
  • 更改 api 以执行多次小上传和完成消息
  • 与它共存