Soap web services client/server code examples

Building and consuming a web service is easy in Visual Studio and other IDEs, but if you find yourself armed with only notepad.exe and needing to retrieve data in an ASP.Net web application via SOAP, the following method is an alternative way of communicating with web services.

First, we need an example web service in written in the language of your choice:

C#
<%@ WebService Language="C#" Class="MyWebservice" %>
using System;
using System.Web.Services;

[WebService(Namespace="http://MyNameSpace/")]
public class MyWebservice : WebService {
  [WebMethod(Description="Returns the sum of two numbers", EnableSession=false)]
  public int Add(int x, int y) {
    return x + y;
  }
}

VB.Net
<%@ WebService Language="VB" Class="MyWebservice" %>
Imports System
Imports System.Web.Services

<WebService(Namespace:="http://MyNameSpace/")> _
Public Class MyWebservice
  Inherits WebService
  <WebMethod(Description := "Returns the sum of two numbers", EnableSession := False)> _
    Public Function Add(x As Integer, y As Integer) As Integer
      Return x + y
    End Function
End Class

Save one of the above as webservice.asmx and put it on a web server with ASP.Net enabled.

To connect to the example web service from a web application and use the example script in the language of your choice: (replace "servername" with the host name of your webservice server)

C#
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Xml" %>
<%@ Page Language="C#" %>

<script runat="server">
public static string WebServiceRequest(string url, string requestBody, string xmlNS, string operation)
{
  string returnText = "";
  try
  {
    HttpWebRequest hwRequest = (HttpWebRequest) WebRequest.Create(url);
    hwRequest.Accept = "*/*";
    hwRequest.AllowAutoRedirect = true;
    hwRequest.UserAgent = "http_requester/0.1";
    hwRequest.Timeout= 60000;
    hwRequest.Method = "POST";
    hwRequest.ContentType = "text/xml; charset=utf-8";
    hwRequest.Headers.Add("SOAPAction", "\"" + xmlNS + operation + "\"");
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] postByteArray = encoding.GetBytes(requestBody);
    hwRequest.ContentLength = postByteArray.Length;
    Stream postStream = hwRequest.GetRequestStream();
    postStream.Write(postByteArray, 0, postByteArray.Length);
    postStream.Close();
    HttpWebResponse hwResponse = (HttpWebResponse) hwRequest.GetResponse();
    if (hwResponse.StatusCode == HttpStatusCode.OK)
    {
      Stream responseStream = hwResponse.GetResponseStream();
      StreamReader myStreamReader = new StreamReader(responseStream);
      returnText = myStreamReader.ReadToEnd();
    }
    hwResponse.Close();
  }
  catch (Exception e)
  {
    returnText = "An error occurred: " + e.Message;
  }
  return returnText;
}
</script>

<%
string xmlRequestData =
  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
  "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + Environment.NewLine +
  "  <soap:Body>" + Environment.NewLine +
  "    <Add xmlns=\"http://MyNameSpace/\">" + Environment.NewLine +
  "      <x>2</x>" + Environment.NewLine +
  "      <y>3</y>" + Environment.NewLine +
  "    </Add>" + Environment.NewLine +
  "  </soap:Body>" + Environment.NewLine +
  "</soap:Envelope>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(WebServiceRequest("http://servername/webservice.asmx", xmlRequestData, "http://MyNameSpace/", "Add"));
XmlNodeList xmlNL = xmlDoc.GetElementsByTagName("AddResult");
for(int i=0; i<xmlNL.Count; i++)
{
  Response.Write("The result is " + xmlNL[i].InnerText);
}
%>

VB.Net
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Xml" %>
<%@ Page Language="VB" %>

<script runat="server">
Function WebServiceRequest(url As String, requestBody As String, xmlNS As String, operation As String) As String
  Dim returnText As String = ""
  Try
    Dim hwRequest As HttpWebRequest = WebRequest.Create(URL)
    hwRequest.Accept = "*/*"
    hwRequest.AllowAutoRedirect = true
    hwRequest.UserAgent = "http_requester/0.1"
    hwRequest.ContentType = "text/xml; charset=utf-8"
    hwRequest.Headers.Add("SOAPAction", """" & xmlNS & operation & """")
    hwRequest.Timeout = 60000
    hwRequest.Method = "POST"
    Dim encoding As New UTF8Encoding()
    Dim postByteArray() As Byte = encoding.GetBytes(requestBody)
    hwRequest.ContentLength = postByteArray.Length
    Dim postStream As Stream = hwRequest.GetRequestStream()
    postStream.Write(postByteArray, 0, postByteArray.Length)
    postStream.Close()
    Dim hwResponse As HttpWebResponse = hwRequest.GetResponse()
    If hwResponse.StatusCode = HttpStatusCode.OK Then
      Dim responseStream As StreamReader = _
        New StreamReader(hwResponse.GetResponseStream())
      returnText = responseStream.ReadToEnd()
    End If
    hwResponse.Close()
    Catch e As Exception
      returnText = "An error occurred: " & e.Message
  End Try
  WebServiceRequest = returnText
End Function
</script>

<%
Dim xmlRequestData As String = _
  "<?xml version=""1.0"" encoding=""utf-8""?>" & vbcrlf & _
  "<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">" & vbcrlf & _
  "  <soap:Body>" & vbcrlf & _
  "    <Add xmlns=""http://MyNameSpace/"">" & vbcrlf & _
  "      <x>2</x>" & vbcrlf & _
  "      <y>3</y>" & vbcrlf & _
  "    </Add>" & vbcrlf & _
  "  </soap:Body>" & vbcrlf & _
  "</soap:Envelope>"
Dim xmlDoc As New XmlDocument
xmlDoc.loadXML(WebServiceRequest("http://servername/webservice.asmx", xmlRequestData, "http://MyNameSpace/", "Add"))
Dim xmlNL As XmlNodeList = xmlDoc.GetElementsByTagName("AddResult")
For i As Integer = 0 To xmlNL.Count - 1
  Response.Write("The result is " & xmlNL(i).InnerText)
Next
%>

Save one of the above as webserviceconsumer.aspx and put it on a web server with ASP.Net enabled. When called, the result will be "5". You can then change the xmlRequestData string, the WebServiceRequest() parameters and XML response handling to interface with other web services.
Tags: aspnet, dotnet
Page last updated 2011-09-19 18:41. Some rights reserved (CC by 3.0)

Search

Feeds

RSS 2.0 feed All content
RSS 2.0 feed ajax
RSS 2.0 feed asp
RSS 2.0 feed aspnet
RSS 2.0 feed bicycle
RSS 2.0 feed copenhagen
RSS 2.0 feed databases
RSS 2.0 feed denmark
RSS 2.0 feed diy
RSS 2.0 feed dotnet
RSS 2.0 feed html
RSS 2.0 feed japan
RSS 2.0 feed javascript
RSS 2.0 feed modding
RSS 2.0 feed photography
RSS 2.0 feed utilities
RSS 2.0 feed vbscript