Daniel Gee
Daniel Gee

Reputation: 438

Error when sending large data with HTTP Post

I am using the following code to send data to an web API from a WinForms app:

private string SendBatch(string URL, string POSTdata)
{
    string responseData = "";
    try
    {
        HttpWebRequest hwrequest = (HttpWebRequest)WebRequest.Create(URL);
        hwrequest.Timeout = 600000;
        hwrequest.KeepAlive = true;
        hwrequest.Method = "POST";
        hwrequest.ContentType = "application/x-www-form-urlencoded";

        byte[] postByteArray = System.Text.Encoding.UTF8.GetBytes("data=" + POSTdata);

        hwrequest.ContentLength = postByteArray.Length;

        System.IO.Stream postStream = hwrequest.GetRequestStream();
        postStream.Write(postByteArray, 0, postByteArray.Length);
        postStream.Close();

        HttpWebResponse hwresponse = (HttpWebResponse)hwrequest.GetResponse();
        if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
        {
            System.IO.StreamReader responseStream = new System.IO.StreamReader(hwresponse.GetResponseStream());
            responseData = responseStream.ReadToEnd();
        }
        hwresponse.Close();
    }
    catch (Exception e)
    {
        responseData = "An error occurred: " + e.Message;
    }
    return responseData;

    }
}

When I send a small amount of data, the API receives the data without any issues. However, when I try to send a large amount of data (30MB+) I get an error from the API that I have sent through malformed data.

I have set the timeout to 10 minutes and I receive the error after around 2 minutes.

According to the questions I have gone through on SO, there isn't a limit to the post size and there is no limit on the API.

I've been trying for a few days to find a solution so any pointers will be GREATLY appreciated.

Thanks!

Upvotes: 3

Views: 7827

Answers (3)

Dijkgraaf
Dijkgraaf

Reputation: 11527

Try setting the HttpWebRequest.SendChunked Property to true.

Upvotes: 0

Chris McKelt
Chris McKelt

Reputation: 1388

If you own the site checkout IIS Request limits

http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="4294967295" />

Upvotes: 1

Marko
Marko

Reputation: 2734

There is a maximum default size to the http post default is set to 4Mg in IIS. You have to change this to allow larger streams.

http://support.microsoft.com/default.aspx?scid=kb;EN-US;295626

Here is an example of how to increase this limit.

IIS 7 httpruntime maxRequestLength limit of 2097151

Upvotes: 2

Related Questions