WebRequest (Follow up to HttpClient)

As a follow up to the previous post; We did find a limitation is our production environment that forced us to switch to a WebRequest instead of using the HttpClient. Given that this was the method we used to replace the functionality:

public XmlDocument SendServiceRequest(string uri, string xmlRequest)
{
    // Prep the request
    byte[] data = Encoding.ASCII.GetBytes(xmlRequest);
 
    // Create the HTTP request
    HttpWebRequest http = (HttpWebRequest) WebRequest.Create(uri);
    http.Method = "POST";
    http.ContentType = "application/xml";
    http.Accept = "application/xml";
    http.ContentLength = data.Length;
 
    // Place the xml into the stream
    using (Stream stream = http.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
 
    // Get the response from the remote
    HttpWebResponse response = (HttpWebResponse) http.GetResponse();
 
    // Process the response stream if available. Create an empty XmlDocument if not
    XmlDocument xmlResponse = new XmlDocument();
 
    using (Stream responseStream = response.GetResponseStream())
    {
        if (responseStream != null)
        {
            using (StreamReader sr = new StreamReader(responseStream))
            {
                xmlResponse.LoadXml(sr.ReadToEnd());
            }
        }
    }
 
    return xmlResponse;
}
Advertisements