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();
url.Append("http://www.gnpcb.org/esv/share/get/");
url.Append("?key=IP");
url.Append("&passage=");
url.Append(System.Web.HttpUtility.UrlEncode(reference));
url.Append("&action=doPassageQuery");
url.Append("&include-passage-references=false");
url.Append("&include-audio-reference=false");
url.Append("&include-footnotes=false");
url.Append("&include-subheadings=false");
url.Append("&include-headings=false");

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();
responseStream.Close();
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.

Post a Comment