Consuming Web Service Using SOAP Request

There are many service available today such as WCF , REST , Web API etc but still Web Service playing very important role in cross platform application communication such as may be you are using  SAP web service to provide data for other platform application.
Download Aspose : API To Create and Convert Files
Previously I have written many articles on web services right from creating to consuming web services and it has huge response , Now in this article we will learn how to consume or call web service using SOAP request with the help of HttpWebRequest class , This approach sometimes we need when consuming the third party web services where we don't know much about the endpoints and configuration of web services . In this article we will not be create any web service because we have already created it So If wants to learn basics of the web services please refer my previous articles.
 I hope you read above articles , Now lets learn how to Call Web Service using SOAP request in console application step by step so beginners also can understand .
Step 1: Find the Web Service SOAP Request Body.

In this article We are not going to create web service because we have already created it and if you wants to create web service and learn about it then please refer my preceding articles.

So lets find out the SOAP request body which is used to pass input parametes and invoke the web service . I have one web service which is hosted in in my local IIS .So paste your web service url into the browser and wait till following response come which is shown in following image.
In the above screen shot , you might be noticed that there are three web methods in the web service named Addition , EmployeeDetails and HelloWorld. Now click on one of the method which you wants to invoke , After clicking on web method it shows SOAP request and SOAP Response body , find out the SOAP request body which is shown in the following image.
In the above image , We are clearly observing that , It shows the all details how to make SOAP request and also showing parameter values which is require to invoke service using HttpWebRequest . So lets learn in brief about those parameters .
Download Aspose : API To Create and Convert Files
  •  HTTP Method: It's nothing but the what type of HTTP request you wants to make to the service such as GET , POST ,PUT or delete.

  •  Host: It defines the url where is the service hosted , in our scenario our host is localhost , i.e http://localhost/Employee.asmx.

  • Content-Type: It defines what type of content type request you are making such as XML or json now in our scenario its text/xml.

  •  Content-Length: It defines the content length of request body.

  •  SOAPAction: This is very important attribute to identify specific web method and call it from multiple web methods .

  • SOAP Body: It contains the request and response body.
I hope you learned about SOAP request parameter , Now copy the soap envelope part to use it as SOAP request which we will use in our console application.

Step 2: Create the Console application to call Web Service
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2015".

  2. "File" - "New" - "Project..." then in the New Project window, console "C#" - ".

  3. Give the project a name, such as "UsingSOAPRequest" or another as you wish and specify the location.
Now open Program.cs file and write the following method to create HttpWebRequest as:
    public HttpWebRequest CreateSOAPWebRequest()    
    {    
        //Making Web Request    
        HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");    
        //SOAPAction    
        Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");    
        //Content_type    
        Req.ContentType = "text/xml;charset=\"utf-8\"";    
        Req.Accept = "text/xml";    
        //HTTP method    
        Req.Method = "POST";    
        //return HttpWebRequest    
        return Req;    
    }    
Now Let's create the method to invoke the web service using SOAP request bo
    public void InvokeService(int a, int b) {  
      //Calling CreateSOAPWebRequest method    
      HttpWebRequest request = CreateSOAPWebRequest();  
      
      XmlDocument SOAPReqBody = new XmlDocument();  
      //SOAP Body Request    
      SOAPReqBody.LoadXml(@ "<?xml version="  
       "1.0"  
       " encoding="  
       "utf-8"  
       "?>   < soap: Envelope xmlns: soap = ""  
       http: //schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">    
       < soap: Body >  
       < Addition xmlns = ""  
       http: //tempuri.org/"">    
       < a > " + a + @" < /a>   < b > " + b + @" < /b>   < /Addition>   < /soap:Body>   < /soap:Envelope>");    
      
      
       using(Stream stream = request.GetRequestStream()) {  
        SOAPReqBody.Save(stream);  
       }  
       //Geting response from request    
       using(WebResponse Serviceres = request.GetResponse()) {  
           using(StreamReader rd = new StreamReader(Serviceres.GetResponseStream())) {  
               //reading stream    
               var ServiceResult = rd.ReadToEnd();  
               //writting stream result on console    
               Console.WriteLine(ServiceResult);  
               Console.ReadLine();  
           }  
       }  
    }  
Now call above method from main method by writing following code as:
    static void Main(string[] args)    
    {    
        //creating object of program class to access methods    
        Program obj = new Program();    
        Console.WriteLine("Please Enter Input values..");    
        //Reading input values from console    
        int a = Convert.ToInt32(Console.ReadLine());    
        int b = Convert.ToInt32(Console.ReadLine());    
        //Calling InvokeService method    
        obj.InvokeService(a, b);    
    }    
Now whole code in Program.cs file will be look like as follows:
using System;  
using System.IO;  
using System.Net;  
using System.Xml;  
  
namespace UsingSOAPRequest  
{  
    public class Program  
    {  
        static void Main(string[] args)  
        {  
            //creating object of program class to access methods  
            Program obj = new Program();  
            Console.WriteLine("Please Enter Input values..");  
            //Reading input values from console  
            int a = Convert.ToInt32(Console.ReadLine());  
            int b = Convert.ToInt32(Console.ReadLine());  
            //Calling InvokeService method  
            obj.InvokeService(a, b);  
        }  
        public void InvokeService(int a, int b)  
        {  
            //Calling CreateSOAPWebRequest method  
            HttpWebRequest request = CreateSOAPWebRequest();  
  
            XmlDocument SOAPReqBody = new XmlDocument();  
            //SOAP Body Request  
            SOAPReqBody.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>  
            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-   instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">  
             <soap:Body>  
                <Addition xmlns=""http://tempuri.org/"">  
                  <a>" + a + @"</a>  
                  <b>" + b + @"</b>  
                </Addition>  
              </soap:Body>  
            </soap:Envelope>");  
  
  
            using (Stream stream = request.GetRequestStream())  
            {  
                SOAPReqBody.Save(stream);  
            }  
            //Geting response from request  
            using (WebResponse Serviceres = request.GetResponse())  
            {  
                using (StreamReader rd = new StreamReader(Serviceres.GetResponseStream()))  
                {  
                    //reading stream  
                    var ServiceResult = rd.ReadToEnd();  
                    //writting stream result on console  
                    Console.WriteLine(ServiceResult);  
                    Console.ReadLine();  
                }  
            }  
        }  
  
        public HttpWebRequest CreateSOAPWebRequest()  
        {  
            //Making Web Request  
            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(@"http://localhost/Employee.asmx");  
            //SOAPAction  
            Req.Headers.Add(@"SOAPAction:http://tempuri.org/Addition");  
            //Content_type  
            Req.ContentType = "text/xml;charset=\"utf-8\"";  
            Req.Accept = "text/xml";  
            //HTTP method  
            Req.Method = "POST";  
            //return HttpWebRequest  
            return Req;  
        }  
    }  
}  
Now run the console application ,then the console windows will be look like as follows and enter the input values as:
 Now press enter button , it will give the response in XML format are as follows:
 In preceding console window you have seen web service response in the form of XML format which contains the output as 300 . I hope from all above example you have learned how to call web service using SOAP request in console application.
Notes
  • Download the Zip file of the sample application for a better understanding.
  • Apply proper validation as per your need.
Summary

I hope this article is useful for all readers , if you have any suggestions related to this article then please contact me.
Read more articles on ASP.NET Web Services

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compile Mode