Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - HttpWebRequest - POST

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.

like image 634
jonathanpeppers Avatar asked Dec 11 '25 12:12

jonathanpeppers


1 Answers

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?

like image 83
Aaronaught Avatar answered Dec 13 '25 04:12

Aaronaught



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!