欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-04 13:18:03
在项目中添加WEB引用耦合度较高,更新时要更新引用,所以我建议不添加WEB引用调用WSDL接口,废话不多说,直接上代码 例如WSDL地址为:http://XXX.XX.XXX.XXX:9115/WsPortal/soap/ws?WSDL 需要调用execute方法 先查看描述文件参数 ///

在项目中添加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);