Connecting to a REST Web Service from .NET

This came up for a project I was doing recently. A lot of .NET developers know how to connect to a SOAP web service, as that is the type of web service Microsoft favors. REST web services, however, are arguably the more popular web services going at the moment, particularly outside of corporate firewalls. Knowing the easy steps it takes to connect to a REST web service in .NET is something you will find quite handy at one point or another.

It’s really quite simple. A REST web service is really just an extended URL call. You simply need to make sure to URL encode the arguments. Here we have a function that does just that:

Private Function AddNumbers(ByVal intA As Integer, ByVal intB As Interger)
Dim strURL As String = “http://your_url/your_webservice.php

strURL &= “?numberA=” & Server.UrlEncode(intA)
strURL &= “&numberB=” & Server.UrlEncode(intB)

Return strURL
End Function

This function passes two numbers to a REST web service. We specify the URL of the web service, and then we tack the arguments on to it (the web service is expecting numberA and numberB as arguments). The Server.UrlEncode function handles any special characters we have, such as spaces or apostrophies, and converts them to their URL equivalent.

That’s it. We can simply call the function and load the result into an XML document (presuming we’re getting an XML document back; a REST service can return all kinds of things).

Dim strURL As String = AddNumbers(5, 3)
Dim xmlDoc As New System.Xml.XmlDocument()
xmlDoc.Load(strURL)

That’s it. We call our function to get the assembled REST URL, then we load the result into an XML document for processing. There a few other tricks for getting to types of REST services that use something other than GET, but those tend to be few and far between.

That’s it. You can now use .NET to tap in to the plethora of REST services out there from the likes of Amazon, Google, Yahoo, and others.