开发者

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 t开发者_如何学Pythonhe 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.


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?


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


I prefer to use a generic method to comply this kind of stuff. Take a look at the XML sender request below. It will serialize your XML and then send it with the appropriate ContentType :

public bool SendXMLRequest<T>(T entity, string url, string method)
{
    HttpWebResponse response = null;
    bool received = false;
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);
        var credCache = new CredentialCache();
        var netCred = new NetworkCredential(YOUR_LOGIN_HERE, YOUR_PASSWORD_HERE, YOUR_OPTIONAL_DOMAIN_HERE);
        credCache.Add(new Uri(url), "Basic", netCred);
        request.Credentials = credCache;
        request.Method = method;
        request.ContentType = "application/xml";
        request.SendChunked = "GET" != method.ToUpper();

        using (var writer = new StreamWriter(request.GetRequestStream()))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            using (StringWriter textWriter = new Utf8StringWriter())
            {
                serializer.Serialize(textWriter, entity);
                var xml = textWriter.ToString();
                writer.Write(xml);
            }
        }

        response = (HttpWebResponse)request.GetResponse();    
        received = response.StatusCode == HttpStatusCode.OK; //YOu can change the status code to check. May be created, etc...
    }
    catch (Exception ex) { }
    finally
    {
        if(response != null)
            response.Close();
        }

    return received;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜