C # - HttpWebRequest - POST

I am trying to do Http POST on an Apache web server.

I find 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 it hangs endlessly.

This 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 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 don't need to set ContentLength? I see no reason to store the XmlWriter 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 had no use of the Stream object returned from GetRequestStream (), I assumed that XmlWriter closed the stream when it was placed, but this is not the case.

One answer below, let me. I will mark them as an answer.

HttpWebRequest, .

+3
2

, . , ? ?

+3

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.sendchunked.aspx, . , , , , . , ?

ContentLength:

: System..::. Int64 -. -1, , .

( ):

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

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));
}
+1

Source: https://habr.com/ru/post/1725641/


All Articles