Question

I am trying to make an Http POST to an Apache web server.

I am finding that setting ContentLength seems to be required for the request to work.

I would rather create an XmlWriter directly from GetRequestStream() and set SendChunked to true, but the request hangs indefinitely when doing so.

Here is how my request is created:

    private HttpWebRequest MakeRequest(string url, string method)
    {
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Method = method;
        request.Timeout = Timeout; //Property in my class, assume it's 10000
        request.ContentType = "text/xml"; //I am only writing xml with XmlWriter
        if (method != WebRequestMethods.Http.Get)
        {
            request.SendChunked = true;
        }
        return request;
    }

How can I make SendChunked work so I do not have to set ContentLength? I do not see a reason to store the XmlWriter's string somewhere before sending it to the server.

EDIT: Here is my code causing the problem:

    using (Stream stream = webRequest.GetRequestStream())
    {
        using (XmlWriter writer = XmlWriter.Create(stream, XmlTags.Settings))
        {
            Generator.WriteXml<TRequest>(request, writer);
        }
    }

Before I did not have a using on the Stream object returned from GetRequestStream(), I assumed XmlWriter closed the stream when disposed, but this is not the case.

One of the answers below, let me to this. I'll mark them as the answer.

As far as HttpWebRequest is concerned, my original code works just fine.

Was it helpful?

Solution

This should work the way you have it written. Can we see the code that actually does the uploading? Are you remembering to close the stream?

OTHER TIPS

Looking at the example at http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.sendchunked.aspx they still set a content length. Really the bottom line is that if you are sending data you need to tell the receiver how much data you will be sending. Why don't you know how much data you are sending before you send the request?

ContentLength:

Property Value Type: System..::.Int64 The number of bytes of data to send to the Internet resource. The default is -1, which indicates the property has not been set and that there is no request data to send.

Edit for Aaron (I was wrong):

HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://test") as HttpWebRequest;
httpWebRequest.SendChunked = true;
MessageBox.Show("|" + httpWebRequest.TransferEncoding + "|");

From System.Net.HttpWebRequest.SerializeHeaders():

if (this.HttpWriteMode == HttpWriteMode.Chunked)
{
    this._HttpRequestHeaders.AddInternal("Transfer-Encoding", "chunked");
}
else if (this.ContentLength >= 0L)
{
    this._HttpRequestHeaders.ChangeInternal("Content-Length", this._ContentLength.ToString(NumberFormatInfo.InvariantInfo));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top