views:

498

answers:

2

I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser.

This is the code which calls the webmethod programmatically:

XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml"); 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());
+2  A: 

Following on from the comments above. If you have a WSDL file that describes your service you use this as the information required to communicate with your web service.

Using a proxy class to communicate with your service proxy is an easy way to abstract yourself from the underlying plumbing of HTTP and XML.

There are ways of doing this at run-time - essentially generating the code that Visual Studio generates when you add a web service reference to your project.

I've used a solution that was based on: this newsgroup question, but there are also other examples out there.

dariom
Yeah that seems like a good approach. Thanks for the answer.
hancock
A: 

FYI, your code is missing using blocks. It should be more like this:

XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml"); 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";

using (Stream reqstm = req.GetRequestStream())
{
    doc.Save(reqstm);
}

using (WebResponse resp = req.GetResponse())
{
    using (Stream respstm = resp.GetResponseStream())
    {
        using (StreamReader r = new StreamReader(respstm))
        {
            Console.WriteLine(r.ReadToEnd());
        }    
    }
}
John Saunders
You're right, but I used dariom's solution which does not employ that piece of code.
hancock