POST requests with large content

Hi all!

I’m using a FEZ Spider with .NET Micro Framework 4.1 and an Ethernet connection to send data to an Azure Mobile Service.

I’m using the following code to send POST requests:

// "serialized" contains a valid JSON string.
var content = POSTContent.CreateTextBasedContent(serialized);
var postRequest = HttpHelper.CreateHttpPostRequest(url, content, "application/json");

postRequest.ResponseReceived += new HttpRequest.ResponseHandler(postRequest_ResponseReceived);

It works fine if the content is small (some KBs). However, if I try to send a content of, say, 20K, the system works for about 30 seconds and then it raises a SocketException without assigning a value to the ErrorCode property. On the Output Window, I can see that a CLR_E_FAIL (8) error has been generated.

To solve the issue, I need to explicitly create an HttpWebRequest and send the request in chunck, with a pause beetween each write:

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Method = "POST";

var serialized = DataContractJsonSerializer.Serialize(obj);
var buffer = System.Text.Encoding.UTF8.GetBytes(serialized);
httpWebRequest.ContentLength = buffer.Length;
httpWebRequest.ContentType = "application/json";
using (Stream stream = httpWebRequest.GetRequestStream())
    int written = 0;
    while (written < buffer.Length)
        int toWrite = System.Math.Min(8192, buffer.Length - written);
        stream.Write(buffer, written, toWrite);
        written += toWrite;

var response = httpWebRequest.GetResponse() as HttpWebResponse;

I have tried with content up to 300K and in this way it works like a charm.

I hope that this trick can be useful :slight_smile:


Thank you. I wonder what is hresult value of the exception?

I don’t remember exactly, but it is a long negative number (started with -14…) that does not correspond to any known socket error.