Many times we see requests coming to find out how to post dynamic web service calls. This is still needed in posting to legacy or proprietary applications that work like web services but are not true web services. Rather, these are applications that are accepting HTTP Posts in SOAP.
The .Net framework makes it a snap to consume web services. In its simplest form, create a proxy and we are almost done. In the case of these dynamic calls, when we can’t create proxies or we don’t have one, we can go back to good old HttpWebRequest in the System.Net namespace module and get our purpose done. Here is a working model that can do this job:
using System.Net;
using System.IO;
using System.Text;
public string HttpSoapCall(string url, string soapMessage, string soapAction)
{
//ASCII Encoding + Bytes:
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteData = encoding.GetBytes(soapMessage);
return HttpSoapCall(url, byteData, soapAction);
}
public string HttpSoapCall(string url, byte[] soapMessage, string soapAction)
{
// HttpWebRequest:
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// If you need proxy:
WebProxy myProxy = new WebProxy("123.45.67.8", 1234);
myProxy.UseDefaultCredentials = true;
myHttpWebRequest.Proxy = myProxy;
// set the Request:
myHttpWebRequest.Headers.Add("MessageType", "CALL");
myHttpWebRequest.Headers.Add("SOAPAction", soapAction);
myHttpWebRequest.ContentType = "text/xml";
myHttpWebRequest.ContentLength = soapMessage.Length;
myHttpWebRequest.Method = "POST";
// GetRequestStream, Write till end and Close:
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(soapMessage, 0, soapMessage.Length);
newStream.Close();
// Get WebResponse and ResponseStream:
WebResponse wRes = myHttpWebRequest.GetResponse();
Stream respStream = wRes.GetResponseStream();
// StreamReader ReadToEnd:
StreamReader reader = new StreamReader(respStream);
string respHTML = reader.ReadToEnd();
respStream.Close();
reader.Close();
wRes.Close();
return respHTML;
}
Well, when in need we do use old methods at times…
Love coding!
1 comment:
Nice one. I also found the following method interesting.
http://techmentis.blogspot.com/2011/05/dynamic-web-service-invoker.html
Post a Comment