Programmatically generating web service calls

Introduction

I recently wanted make a call to a third party web service without the use of a proxy class. The code shown in this post will allow you to programmatically build and submit a web service call using the HttpRequest class.

Import Namespaces

Add the following lines to import the required namespaces

usingSystem.Net;
using System.IO;

Build an HTTP Request

The first step is to create an HttpWebRequest, you’ll notice we add a SOAPAction header specifying which method we want to run.

//Build Request and headers
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://service.com/service.asmx");
webRequest.Headers.Add("SOAPAction", "MethodNameAction");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";

If you need to specify a proxy to use you can also do this here

webRequest.Proxy = new WebProxy(http://myproxy.internal:3128);

Populate the Request

Now we need to write the content to post into the request stream, you will need to replace the GetRequestBody() call with a method that returns the text that forms your request

//Write body to the request stream
string body = GetRequestBody();
using(StreamWriter str = new StreamWriter(webRequest.GetRequestStream()))
{str.Write(body);}

Submit the Request

Next we sumbit our request and wait for the response

//Submit Request
IAsyncResult result = webRequest.BeginGetResponse(null, null);

//Insert anything here that needs to happen while the request
//is being processed (GUI updates etc)
result.AsyncWaitHandle.WaitOne();
WebResponse webResponse = webRequest.EndGetResponse(result);
 

If you don't need to do any processing while you wait for the response you can replace the three lines of code above with the following line; 


//Submit Request
WebResponse webResponse = webRequest.GetResponse();

Get the Response Body

Now all we need to do is grab the response back out of the response stream

//Extract Response
StreamReader rd = new StreamReader(webResponse.GetResponseStream());