Search This Blog

Monday, November 7, 2011

WebService - Ways to communicate

Various Ways to communicate to WebService :-

1. Using Proxy to send Soap request/response

2. HttpGet

3. HttpPost

1. Using Proxy:
Create a proxy through VS environment and create an object of proxy class. Call the methods through proxy class.


2. Using HttpGet:
Enable HttpGet in Web.confing at web service level







Send the request through url to WebService like the one below:-

http://localhost/service.asmx/Add?a=1&b=2

localhost - server
service.asmx - service name
Add - Method in Webservice which is being called
a, b - Parameters that Add method expects. Parameters are not taken by order, but they are taken by name

In the above case we have a method called as Add(int a, int b).

3. Using HttpPost:
Enable HttpPost in Web.confing at web service level

    
      
         
      
    


Code for Client to Post data to WebService:-

//Creating the Web Request.
HttpWebRequest httpWebRequest = HttpWebRequest.Create("http://localhost/WS1/Service.asmx/Add") as HttpWebRequest;

//Specifing the Method
httpWebRequest.Method = "POST";

//Data to Post to the Page, itis key value pairs; separated by "&"
string data = "a=gj&b=gj1";

//Setting the content type, it is required, otherwise it will not work.
httpWebRequest.ContentType = "application/x-www-form-urlencoded";

//Getting the request stream and writing the post data
using (StreamWriter sw = new StreamWriter(httpWebRequest.GetRequestStream()))
{
sw.Write(data);
}
//Getting the Respose and reading the result.
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream()))
{
lblMessage.Text = sr.ReadToEnd();
}

No comments:

Post a Comment