Thursday 7 June 2007

Basic Web Service Access From C#

I recently wrote a small plugin for Windows Live Writer, which allowed you to enter a Bible reference, and it would either create a link to Bible Gateway, or insert the text in the English Standard Version.

To get the ESV text, I needed to call a web service in C#. It was the first time I had done this, and it turned out to be surprisingly simple. First I needed to construct the URL to call. This was simply a case of constructing the ESV Web Service API documentation. The only slight complication is the need to add a reference to System.Web so you can call HttpUtility.UrlEncode.

StringBuilder url = new StringBuilder();

Once you have the URL with the search parameters, then you simply pass it to a web request, get its ResponseStream() and read it to the end.

WebRequest request = WebRequest.Create(url.ToString());
StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream());
String response = responseStream.ReadToEnd();
return response.ToString();

Obviously there are more complicated types of web service than this, which require construction and parsing of XML, but I was still impressed with how few lines of code were actually involved in my first web service call.

1 comment:

Robbalman said...

Thanks for the post, it was very helpful.