Writing SOAP request from scratch

I had to test a few web services today and the test data was in the form of several XML files containing the actual SOAP envelope. I googled to see if I could find a simple enough tool on the web with no success. Eventually, I had to write my own :(.

Here is a bit of code that may come in handy to someone someday –

    HttpWebRequest request = (HttpWebRequest) 

    String xmlString = txtInput.Text; 
    ASCIIEncoding encoding = new ASCIIEncoding(); 

    byte[] bytesToWrite = encoding.GetBytes(xmlString); 

    request.Method = "POST"; 
    request.ContentLength = bytesToWrite.Length; 
    request.Headers.Add("SOAPAction: \"http://localhost/XXX/ActionName\""); //You need to change this 
    request.ContentType = "text/xml; charset=utf-8"; 

    Stream newStream = request.GetRequestStream(); 
    newStream.Write(bytesToWrite, 0, bytesToWrite.Length); 

    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
    Stream dataStream = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(dataStream); 

    string responseFromServer = reader.ReadToEnd();

The code is actually quite straight forward. I create a HttpWebRequest and set some basic settings such as the content length and type. The one key thing is to add the SOAPAction in the http’s header. Once that is done, all we need to do is send the request to the url.