Consume Web services Dynamically using HttpWebRequest


Hello Developers,

Here in this article I am going to explain about dynamic invocation of web services using HttpWebRequest.

.NET gives a very easier way to consume web services by Add Web Reference feature. Then we create a proxy class to communicate with the different WEBMETHODS.

For Example:

MyWebServices.Service objService = new MyWebServices.Service();
objService.MyWebMethod();

But we’ll not follow the above way, we’ll use HttpWebRequest to consume the web service.

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

For an instance:

Webservice URL: http://mysite.com/mywebservices/service.asmx

WebMethods: MyMethod()

Request MetaData:

POST /mywebservices/service.asmx HTTP/1.1
Host: myservicehost.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://mysite.com/MyMethod"

<?xml version="1.0" encoding="utf-8"?>
<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/">
  <soap:Body>
    <MyMethod xmlns="http://mysite.com/" />
  </soap:Body>
</soap:Envelope>

Response metadata:

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

<?xml version="1.0" encoding="utf-8"?>
<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/">
  <soap:Body>
    <MyMethodResponse xmlns="http://mysite.com/">
      <MyMethodResult>string</MyMethodResult>
    </MyMethodResponse>
  </soap:Body>
</soap:Envelope>

So now whenever you are requesting the service your SOAP request and response metadata has to be like the above.

From metedata you can recognize that it’s a POST action. Below is the c# code for consuming this particular web service.

//prepare your request envelop

byte[] buffer = Encoding.ASCII.GetBytes(@”<?xml version=””1.0″” encoding=””utf-8″”?>
<soap:Envelope xmlns:xsi=””http://www.w3.org/2001/XMLSchema-instance”&#8221;
xmlns:xsd=””http://www.w3.org/2001/XMLSchema”&#8221;
xmlns:soap=””http://schemas.xmlsoap.org/soap/envelope/””&gt;
<soap:Body>
<MyMethod xmlns=””http://mysite.com/”&#8221; />
</soap:Body>
</soap:Envelope>”);
//Initialization, webrequest
HttpWebRequest WebReq =
(HttpWebRequest)WebRequest.Create(“http://myite.com/mywebservices/service.asmx&#8221;);

//Set the method/action type
WebReq.Method = “POST”;

//We use form contentType
WebReq.ContentType = “text/xml; charset=utf-8”;

//The length of the buffer
WebReq.ContentLength = buffer.Length;

//We open a stream for writing the post  data
Stream MyPostData = WebReq.GetRequestStream();

//Now we write, and after wards, we close. Closing is always important!
MyPostData.Write(buffer, 0, buffer.Length);
MyPostData.Close();

//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

//Now, we read the response (the string), and output it.
Stream MyResponse = WebResp.GetResponseStream();
StreamReader MyResponseReader = new StreamReader(MyResponse);

//Read the response Stream and write it
Response.Write(MyResponseReader.ReadToEnd());

The GetResponse method makes a synchronous request to the Internet resource specified in the RequestUri property and returns an HttpWebResponse instance containing the response. You can make an asynchronous request to the Internet resource using the BeginGetResponse and EndGetResponse methods.

When you want to send data to the Internet resource, the GetRequestStream method returns a Stream instance to use to send data. The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data stream.

Now we will know about HTTP GET Webrequest, please look at the below example,

WebService URL: http://service.mydomain.com/somedirectory/getitem?itemID=1109&itemCategoryID=201

As you see the service URL, it would be a GET request and  is appended with two Request Parameters i;e itemID and itemCategoryID.

Now you can see the below code to consume this particular service using HttpWebRequest and reading the response using HttpWebResponse.

//service URL

string URI = “http://service.mydomain.com/somedirectory/getitem?itemID=1109&itemCategoryID=201&#8221;;

//creating the proxy for the service call using the HttpWebRequest class
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(URI);

//Set the method/action type
WebReq.Method = “GET”;

//We use form contentType
WebReq.ContentType = “text/xml; charset=utf-8”;

//Get the response handle, we have no true response yet!
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

//Now, we read the response (the string), and output it.
Stream MyResponse = WebResp.GetResponseStream();

//read the stream into streamreader
StreamReader MyResponseReader = new StreamReader(MyResponse);

//Loading into XML doc
XDocument xmlDoc = XDocument.Load(MyResponseReader);

//read the XML nodes using Linq
var itemList= from content in xmlDoc.Descendants(“item”)//node
select new
{
itemName = content.Element(“itemName “).Value,
categoryName= content.Element(“categoryName”).Value,
itemImage= content.Element(“itemImage”).Value,
};

Then you can use the anonymous variable( itemList) as you wish. Here I have used LINQ to XML concept to read through the XML response.

For more details on the HttpWebrequest class properties please visit the below site

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.71%29.aspx

Thanks for reading this article.

Enjoy 🙂

Swagat Parida

MyMethodResult
Advertisements