简体   繁体   中英

Make HttpWebRequest ignoring response

I have a custom WebUploadTraceListener : TraceListener that I use to send HTTP (and eventually HTTPS) POST data to a web service that writes it to a database.

I have tested doing this with both WebClient and HttpWebRequest and empirically I'm seeing better performance with the latter.

Because of the one-way nature of the data, I don't care about the server response. But I found that if I don't handle the HttpWebResponse my code locks up on the third write. I think this is because of the DefaultConnectionLimit setting and the system not reusing the resource...

Per Jon Skeet

Note that you do need to dispose of the WebResponse returned by request.GetResponse - otherwise the underlying infrastructure won't know that you're actually done with it, and won't be able to reuse the connection.

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(ServiceURI);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";

try
{
    using (Stream stream = httpRequest.GetRequestStream())
    {
        stream.Write(postBytes, 0, postBytes.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse())
    {
        /// discard response
    }
}
catch (Exception)
{
    /// ...
}

I want to maximize the speed of sending the POST data and get back to the main program flow as quickly as possible. Because I'm tracing program flow, a synchronous write is preferable, but not mandatory as I can always add a POST field including a Tick count.

  1. Is an HttpWebRequest and stream.Write the quickest method for doing this in .Net4.0 ?
  2. Is there a cheaper way of discarding the unwanted response?

Attually, httpRequest.GetResponse only post the data to server and don't download anything to the client, except the information to tell client if the request is successfully processed by server.

You only get the respone data when you call GetResponseStream . If even the information about the success/error of the request you don't want to received, you don't have anyway to tell if server is success process the request or not.

So the answer is:

  1. Yes, that is lowest level for managed code, unless you want mess up with socket (which you shouldn't)
  2. With HttpWebRequest , no. You almost don't get any data you don't want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM