5

我正在尝试编写一个函数,该函数可以在给定方法的名称和 Web 服务的 URL 的情况下从 Web 服务调用 Web 方法。我在博客上找到了一些代码,除了一个细节外,它做得很好。它还要求提供请求 XML。这里的目标是从 web 服务本身获取请求 XML 模板。我确信这是可能的,因为如果我在浏览器中访问 Web 服务的 URL,我可以同时看到请求和响应 XML 模板。

这是以编程方式调用 webmethod 的代码:

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());
4

2 回答 2

2

根据上面的评论。如果您有一个描述您的服务的 WSDL 文件,您可以使用它作为与您的 Web 服务通信所需的信息。

使用代理类与您的服务代理进行通信是一种将您自己从 HTTP 和 XML 的底层管道中抽象出来的简单方法。

有一些方法可以在运行时执行此操作 - 本质上是在您向项目添加 Web 服务引用时生成 Visual Studio 生成的代码。

我使用的解决方案基于:this newsgroup question,但也有其他示例

于 2010-06-04T12:40:27.730 回答
0

仅供参考,您的代码缺少using块。它应该更像这样:

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());
        }    
    }
}
于 2010-06-08T21:25:30.893 回答