开发者

C#: How to POST large string via WebRequest?

how can i upload a large string (in my case XML with BLOB) with POST without getting Timeout with GetResponse?

Changing the timeout helps, but this isn't really a solution. If the Server is really death or the POST was interrupted i have to wait for the extrem large timeout.

Any Idea?

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(webRes开发者_如何学运维ponse.GetResponseStream()))
        {
            response = sr.ReadToEnd().Trim();
            sr.Close();
        }
        webResponse.Close();
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.ToString());
}
return response;


Yes, this is pretty much expected http behaviour.

Options:

  • have a large timeout (you've already done this), and accept that it could take a long time to legitimately time out (as opposed to taking a while because of bandwidth)
  • maybe you can apply gzip on the request (and tell the server you're sending it compressed); I honestly don't know if this is supported automatically, but it could certainly be done by the api explicitly checking for a particular header and applying gzip decompression on the payload
  • change the api to perform a number of small uploads, and a completion message
  • live with it
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜