C# 不添加WEB引用调用WSDL接口

在项目中添加WEB引用耦合度较高,更新时要更新引用,所以我建议不添加WEB引用调用WSDL接口,废话不多说,直接上代码

例如WSDL地址为:http://XXX.XX.XXX.XXX:9115/WsPortal/soap/ws?WSDL    需要调用execute方法  先查看描述文件参数

/// <summary>
        /// 需要WebService支持Post调用
        /// </summary>
        public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            SetWebRequest(request);
            byte[] data = EncodePars(Pars);
            WriteRequestData(request, data);
            return ReadXmlResponse(request.GetResponse());
        }

        /// <summary>
        /// 需要WebService支持Get调用
        /// </summary>
        public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            SetWebRequest(request);
            return ReadXmlResponse(request.GetResponse());
        }

        /// <summary>
        /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
        /// </summary>
        public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
        {
            if (_xmlNamespaces.ContainsKey(URL))
            {
                return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
            }
            else
            {
                return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
            }
        }

        private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
        {
            _xmlNamespaces[URL] = XmlNs;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "text/xml; charset=utf-8";
            request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
            SetWebRequest(request);
            byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
            WriteRequestData(request, data);
            XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
            doc = ReadXmlResponse(request.GetResponse());

            XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
            mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
            String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
            doc2.LoadXml("<root>" + RetXml + "</root>");
            AddDelaration(doc2);
            return doc2;
        }
        private static string GetNamespace(String URL)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
            SetWebRequest(request);
            WebResponse response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sr.ReadToEnd());
            sr.Close();
            return doc.SelectSingleNode("//@targetNamespace").Value;
        }

        private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<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:Envelope>");
            AddDelaration(doc);
            XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
            XmlElement soapMethod = doc.CreateElement(MethodName);
            soapMethod.SetAttribute("xmlns", XmlNs);
            foreach (string k in Pars.Keys)
            {
                XmlElement soapPar = doc.CreateElement(k);
                soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
                soapMethod.AppendChild(soapPar);
            }
            soapBody.AppendChild(soapMethod);
            doc.DocumentElement.AppendChild(soapBody);
            return Encoding.UTF8.GetBytes(doc.OuterXml);
        }
        private static string ObjectToSoapXml(object o)
        {
            XmlSerializer mySerializer = new XmlSerializer(o.GetType());
            MemoryStream ms = new MemoryStream();
            mySerializer.Serialize(ms, o);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
            if (doc.DocumentElement != null)
            {
                return doc.DocumentElement.InnerXml;
            }
            else
            {
                return o.ToString();
            }
        }

        /// <summary>
        /// 设置凭证与超时时间
        /// </summary>
        /// <param name="request"></param>
        private static void SetWebRequest(HttpWebRequest request)
        {
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
        }

        private static void WriteRequestData(HttpWebRequest request, byte[] data)
        {
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
        }

        private static byte[] EncodePars(Hashtable Pars)
        {
            return Encoding.UTF8.GetBytes(ParsToString(Pars));
        }

        private static String ParsToString(Hashtable Pars)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }
            }
            return sb.ToString();
        }

        private static XmlDocument ReadXmlResponse(WebResponse response)
        {
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(retXml);
            return doc;
        }

        private static void AddDelaration(XmlDocument doc)
        {
            XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
            doc.InsertBefore(decl, doc.DocumentElement);
        }

        private static Hashtable _xmlNamespaces = new Hashtable();

使用:

1 //以XML参数类型为例,其他太简单
2 string xml = request.ToXml("RequestParameter").ToString();
3             Hashtable ht = new Hashtable();
4             ht.Add("arg0", xml);
5             XmlDocument xd =QuerySoapWebService("地址","方法" , ht);

原文地址:https://www.cnblogs.com/cx36727/p/10689427.html

时间: 2024-08-02 09:55:13

C# 不添加WEB引用调用WSDL接口的相关文章

asp.net调用web service不通过添加web引用的方式怎么调用

创建方法 //动态调用web服务 public static object InvokeWebSer(string url,string @namespace, string classname, string methodname, object[] args) { System.Net.WebClient wc = new System.Net.WebClient(); string URL=string.Empty; if ((url.Substring(url.Length - 5, 5

添加web引用和添加服务引用有什么区别?

添加web引用和添加服务引用有什么区别,Add Service References 和 Add Web References 有啥区别?参考 http://social.microsoft.com/Forums/zh-CN/xmlwebserviceszhchs/thread/808d870b-49f1-47ac-b105-4beb580bcec6 (1)VS2005里提供的Add Web Reference(添加Web服务引用)的功能主要是添加Web Service引用.(2)VS2008保

.net 添加web引用和添加服务引用有什么区别?

添加web引用和添加服务引用有什么区别, Add Service References 和 Add Web References 有啥区别? 参考 http://social.microsoft.com/Forums/zh-CN/xmlwebserviceszhchs/thread/808d870b-49f1-47ac-b105-4beb580bcec6(1)VS2005里提供的Add Web Reference(添加Web服务引用)的功能主要是添加Web Service引用. (2)VS200

C#/Java 调用WSDL接口及方法

一.C#利用vs里面自带的"添加web引用"功能: 1.首先需要清楚WSDL的引用地址  如:http://www.webxml.com.cn/Webservices/WeatherWebService.asmx 2.在.Net项目中,添加web引用. 3.在弹出页面中,输入URL->点击点击绿色图标(前往)按钮->自定义引用名->点击添加引用 4.添加成功,查看类中可调用的方法: 5.在项目中,调用wsdl中的方法. [csharp] view plain copy

(转)添加服务引用和添加Web引用对比

在WindowsForm程序中添加服务引用和Web引用对比 为了验证书上有关Visual Studio 2010添加服务引用和Web引用的区别,进行实验. 一.建立一个Web服务程序项目新建项目,选择ASP.NET空Web应用程序,在其中添加Web服务,然后发布到IIS,路径为http://localhost/hello/hello.asmx,服务主要通过HelloWorld()方法输出字符串“Hello World”,内容如下: using System;using System.Collec

添加服务引用和添加Web引用对比

原文:添加服务引用和添加Web引用对比 在WindowsForm程序中添加服务引用和Web引用对比 为了验证书上有关Visual Studio 2010添加服务引用和Web引用的区别,进行实验. 一.建立一个Web服务程序项目新建项目,选择ASP.NET空Web应用程序,在其中添加Web服务,然后发布到IIS,路径为http://localhost/hello/hello.asmx,服务主要通过HelloWorld()方法输出字符串"Hello World",内容如下: using S

VS2010 webservice 添加web引用

VS2010中只有添加服务引用,那如何添加web引用呢? < XMLNAMESPACE PREFIX ="[default]" httpwwwworgxhtml NS ="http://www.w3.org/1999/xhtml" />在“项目”菜单中,单击“添加服务引用”. 在“添加服务引用”对话框中,单击“高级”. 在“服务引用设置”对话框中,单击“添加 Web 引用”. 在“添加 Web 引用”对话框的 URL 框中,键入URL,如 http://

WCF无.SVC文件服务激活,及不添加服务引用调用WCF

一,新建WCF服务引用程序 1,删除.svc文件,全部删除. 2,新建 IService 类 namespace TestWcf { [ServiceContract] public interface IService { [OperationContract] string DoWork(); } } 3,实现接口类 Service类 namespace TestWcf { public class Service : IService { public string DoWork() {

java调用wsdl接口

前提: ① 已经提供了一个wsdl接口 ② 该接口能正常调用 步骤1:使用cxf的wsdl2java工具生成本地类 下载CXF:http://cxf.apache.org/download.html 配置环境变量: CXF_HOME=E:\WebService\CXF\apache-cxf-2.1.1\apache-cxf-2.1.1 PATH后追加上“ ;%CXF_HOME%\bin” 验证:cmd命令行中输入wsdl2java,如果显示其用法表示配置好了. 运行命令 : wsdl2java