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

深入.net调用webservice的总结分析

程序员文章站 2024-03-01 12:50:40
最近做一个项目,由于是在别人框架里开发app,导致了很多限制,其中一个就是不能直接引用webservice 。我们都知道,调用webserivice 最简单的方法就是在 "...
最近做一个项目,由于是在别人框架里开发app,导致了很多限制,其中一个就是不能直接引用webservice 。
我们都知道,调用webserivice 最简单的方法就是在 "引用"  那里点击右键,然后选择"引用web服务",再输入服务地址。
确定后,会生成一个app.config 里面就会自动生成了一些配置信息。
现在正在做的这个项目就不能这么干。后来经过一番搜索,就找出另外几种动态调用webservice 的方法。
废话少说,下面是webservice 代码
复制代码 代码如下:

view code
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.services;
namespace testwebservice
{
    /// <summary>
    /// service1 的摘要说明
    /// </summary>
    [webservice(namespace = "http://tempuri.org/",description="我的web服务")]
    [webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
    [system.componentmodel.toolboxitem(false)]
    // 若要允许使用 asp.net ajax 从脚本中调用此 web 服务,请取消对下行的注释。
    // [system.web.script.services.scriptservice]
    public class testwebservice : system.web.services.webservice
    {
        [webmethod]
        public string helloworld()
        {
            return "测试hello world";
        }
        [webmethod]
        public string test()
        {
            return "测试test";
        }

        [webmethod(cacheduration = 60,description = "测试")]
        public list<string> getpersons()
        {
            list<string> list = new list<string>();
            list.add("测试一");
            list.add("测试二");
            list.add("测试三");
            return list;
        } 
    }
}

动态调用示例:
方法一:
看到很多动态调用webservice都只是动态调用地址而已,下面发一个不光是根据地址调用,方法名也可以自己指定的,主要原理是根据指定的webservice地址的wsdl,然后解析模拟生成一个代理类,通过反射调用里面的方法
复制代码 代码如下:

view code
using system;
using system.io;
using system.collections.generic;
using system.linq;
using system.collections;
using system.web;
using system.net;
using system.reflection;
using system.codedom;
using system.codedom.compiler;
using system.web.services;
using system.text;
using system.web.services.description;
using system.web.services.protocols;
using system.xml.serialization;
using system.windows.forms;
namespace consoleapplication1
{
    class program
    {
        static void main(string[] args)
        {
            webclient client = new webclient();
            string url = "http://localhost:3182/service1.asmx?wsdl";//这个地址可以写在config文件里面,这里取出来就行了.在原地址后面加上: ?wsdl
            stream stream = client.openread(url);
            servicedescription description = servicedescription.read(stream);
            servicedescriptionimporter importer = new servicedescriptionimporter();//创建客户端代理代理类。
            importer.protocolname = "soap"; //指定访问协议。
            importer.style = servicedescriptionimportstyle.client; //生成客户端代理。
            importer.codegenerationoptions = codegenerationoptions.generateproperties | codegenerationoptions.generatenewasync;
            importer.addservicedescription(description, null, null); //添加wsdl文档。
            codenamespace nmspace = new codenamespace(); //命名空间
            nmspace.name = "testwebservice";
            codecompileunit unit = new codecompileunit();
            unit.namespaces.add(nmspace);
            servicedescriptionimportwarnings warning = importer.import(nmspace, unit);
            codedomprovider provider = codedomprovider.createprovider("csharp");
            compilerparameters parameter = new compilerparameters();
            parameter.generateexecutable = false;
            parameter.outputassembly = "mytest.dll";//输出程序集的名称
            parameter.referencedassemblies.add("system.dll");
            parameter.referencedassemblies.add("system.xml.dll");
            parameter.referencedassemblies.add("system.web.services.dll");
            parameter.referencedassemblies.add("system.data.dll");
            compilerresults result = provider.compileassemblyfromdom(parameter, unit);
            if (result.errors.haserrors)
            {
                // 显示编译错误信息
            }
            assembly asm = assembly.loadfrom("mytest.dll");//加载前面生成的程序集
            type t = asm.gettype("testwebservice.testwebservice");
            object o = activator.createinstance(t);
            methodinfo method = t.getmethod("getpersons");//getpersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下
            string[] item = (string[])method.invoke(o, null);
            //注:method.invoke(o, null)返回的是一个object,如果你服务端返回的是dataset,这里也是用(dataset)method.invoke(o, null)转一下就行了,method.invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的
            foreach (string str in item)
                console.writeline(str);
            //上面是根据webservice地址,模似生成一个代理类,如果你想看看生成的代码文件是什么样子,可以用以下代码保存下来,默认是保存在bin目录下面
            textwriter writer = file.createtext("mytest.cs");
            provider.generatecodefromcompileunit(unit, writer, null);
            writer.flush();
            writer.close();
        }
    }
}

方法二:利用 wsdl.exe生成webservice代理类:
根据提供的wsdl生成webservice代理类,然后在代码里引用这个类文件。
步骤:
1、在开始菜单找到  microsoft visual studio 2010 下面的visual studio tools , 点击visual studio 命令提示(2010),打开命令行。
2、 在命令行中输入:  wsdl /language:c# /n:testdemo /out:d:/temp/testservice.cs http://jm1.services.gmcc.net/ad/services/ad.asmx?wsdl
这句命令行的意思是:对最后面的服务地址进行编译,在d盘temp 目录下生成testservice文件。
3、 把上面命令编译后的cs文件,复制到我们项目中,在项目代码中可以直接new 一个出来后,可以进行调用。
贴出由命令行编译出来的代码:
复制代码 代码如下:

view code
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由工具生成。
//     运行时版本:4.0.30319.225
//
//     对此文件的更改可能会导致不正确的行为,并且如果
//     重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
//
// 此源代码由 wsdl 自动生成, version=4.0.30319.1。
//
namespace bingosoft.module.surveyquestionnaire.dal {
    using system;
    using system.diagnostics;
    using system.xml.serialization;
    using system.componentmodel;
    using system.web.services.protocols;
    using system.web.services;
    using system.data;

   
    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    [system.web.services.webservicebindingattribute(name="webserviceforilooksoap", namespace="http://tempuri.org/")]
    public partial class webserviceforilook : system.web.services.protocols.soaphttpclientprotocol {

        private system.threading.sendorpostcallback getrecordnumoperationcompleted;

        private system.threading.sendorpostcallback getvotelistoperationcompleted;

        private system.threading.sendorpostcallback voteoperationcompleted;

        private system.threading.sendorpostcallback giveupoperationcompleted;

        private system.threading.sendorpostcallback getquestiontasklistoperationcompleted;

        /// <remarks/>
        public webserviceforilook() {
            this.url = "http://st1.services.gmcc.net/qnaire/services/webserviceforilook.asmx";
        }

        /// <remarks/>
        public event getrecordnumcompletedeventhandler getrecordnumcompleted;

        /// <remarks/>
        public event getvotelistcompletedeventhandler getvotelistcompleted;

        /// <remarks/>
        public event votecompletedeventhandler votecompleted;

        /// <remarks/>
        public event giveupcompletedeventhandler giveupcompleted;

        /// <remarks/>
        public event getquestiontasklistcompletedeventhandler getquestiontasklistcompleted;

        /// <remarks/>
        [system.web.services.protocols.soapdocumentmethodattribute("http://tempuri.org/getrecordnum", requestnamespace="http://tempuri.org/", responsenamespace="http://tempuri.org/", use=system.web.services.description.soapbindinguse.literal, parameterstyle=system.web.services.protocols.soapparameterstyle.wrapped)]
        public int[] getrecordnum(string appcode, string userid) {
            object[] results = this.invoke("getrecordnum", new object[] {
                        appcode,
                        userid});
            return ((int[])(results[0]));
        }

        /// <remarks/>
        public system.iasyncresult begingetrecordnum(string appcode, string userid, system.asynccallback callback, object asyncstate) {
            return this.begininvoke("getrecordnum", new object[] {
                        appcode,
                        userid}, callback, asyncstate);
        }

        /// <remarks/>
        public int[] endgetrecordnum(system.iasyncresult asyncresult) {
            object[] results = this.endinvoke(asyncresult);
            return ((int[])(results[0]));
        }

        /// <remarks/>
        public void getrecordnumasync(string appcode, string userid) {
            this.getrecordnumasync(appcode, userid, null);
        }

        /// <remarks/>
        public void getrecordnumasync(string appcode, string userid, object userstate) {
            if ((this.getrecordnumoperationcompleted == null)) {
                this.getrecordnumoperationcompleted = new system.threading.sendorpostcallback(this.ongetrecordnumoperationcompleted);
            }
            this.invokeasync("getrecordnum", new object[] {
                        appcode,
                        userid}, this.getrecordnumoperationcompleted, userstate);
        }

        private void ongetrecordnumoperationcompleted(object arg) {
            if ((this.getrecordnumcompleted != null)) {
                system.web.services.protocols.invokecompletedeventargs invokeargs = ((system.web.services.protocols.invokecompletedeventargs)(arg));
                this.getrecordnumcompleted(this, new getrecordnumcompletedeventargs(invokeargs.results, invokeargs.error, invokeargs.cancelled, invokeargs.userstate));
            }
        }

        /// <remarks/>
        [system.web.services.protocols.soapdocumentmethodattribute("http://tempuri.org/getvotelist", requestnamespace="http://tempuri.org/", responsenamespace="http://tempuri.org/", use=system.web.services.description.soapbindinguse.literal, parameterstyle=system.web.services.protocols.soapparameterstyle.wrapped)]
        public system.data.dataset getvotelist(string appcode, string userid) {
            object[] results = this.invoke("getvotelist", new object[] {
                        appcode,
                        userid});
            return ((system.data.dataset)(results[0]));
        }

        /// <remarks/>
        public system.iasyncresult begingetvotelist(string appcode, string userid, system.asynccallback callback, object asyncstate) {
            return this.begininvoke("getvotelist", new object[] {
                        appcode,
                        userid}, callback, asyncstate);
        }

        /// <remarks/>
        public system.data.dataset endgetvotelist(system.iasyncresult asyncresult) {
            object[] results = this.endinvoke(asyncresult);
            return ((system.data.dataset)(results[0]));
        }

        /// <remarks/>
        public void getvotelistasync(string appcode, string userid) {
            this.getvotelistasync(appcode, userid, null);
        }

        /// <remarks/>
        public void getvotelistasync(string appcode, string userid, object userstate) {
            if ((this.getvotelistoperationcompleted == null)) {
                this.getvotelistoperationcompleted = new system.threading.sendorpostcallback(this.ongetvotelistoperationcompleted);
            }
            this.invokeasync("getvotelist", new object[] {
                        appcode,
                        userid}, this.getvotelistoperationcompleted, userstate);
        }

        private void ongetvotelistoperationcompleted(object arg) {
            if ((this.getvotelistcompleted != null)) {
                system.web.services.protocols.invokecompletedeventargs invokeargs = ((system.web.services.protocols.invokecompletedeventargs)(arg));
                this.getvotelistcompleted(this, new getvotelistcompletedeventargs(invokeargs.results, invokeargs.error, invokeargs.cancelled, invokeargs.userstate));
            }
        }

        /// <remarks/>
        [system.web.services.protocols.soapdocumentmethodattribute("http://tempuri.org/vote", requestnamespace="http://tempuri.org/", responsenamespace="http://tempuri.org/", use=system.web.services.description.soapbindinguse.literal, parameterstyle=system.web.services.protocols.soapparameterstyle.wrapped)]
        public bool vote(string appcode, string userid, string qtaskid, string answer) {
            object[] results = this.invoke("vote", new object[] {
                        appcode,
                        userid,
                        qtaskid,
                        answer});
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public system.iasyncresult beginvote(string appcode, string userid, string qtaskid, string answer, system.asynccallback callback, object asyncstate) {
            return this.begininvoke("vote", new object[] {
                        appcode,
                        userid,
                        qtaskid,
                        answer}, callback, asyncstate);
        }

        /// <remarks/>
        public bool endvote(system.iasyncresult asyncresult) {
            object[] results = this.endinvoke(asyncresult);
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public void voteasync(string appcode, string userid, string qtaskid, string answer) {
            this.voteasync(appcode, userid, qtaskid, answer, null);
        }

        /// <remarks/>
        public void voteasync(string appcode, string userid, string qtaskid, string answer, object userstate) {
            if ((this.voteoperationcompleted == null)) {
                this.voteoperationcompleted = new system.threading.sendorpostcallback(this.onvoteoperationcompleted);
            }
            this.invokeasync("vote", new object[] {
                        appcode,
                        userid,
                        qtaskid,
                        answer}, this.voteoperationcompleted, userstate);
        }

        private void onvoteoperationcompleted(object arg) {
            if ((this.votecompleted != null)) {
                system.web.services.protocols.invokecompletedeventargs invokeargs = ((system.web.services.protocols.invokecompletedeventargs)(arg));
                this.votecompleted(this, new votecompletedeventargs(invokeargs.results, invokeargs.error, invokeargs.cancelled, invokeargs.userstate));
            }
        }

        /// <remarks/>
        [system.web.services.protocols.soapdocumentmethodattribute("http://tempuri.org/giveup", requestnamespace="http://tempuri.org/", responsenamespace="http://tempuri.org/", use=system.web.services.description.soapbindinguse.literal, parameterstyle=system.web.services.protocols.soapparameterstyle.wrapped)]
        public bool giveup(string appcode, string userid, string qtaskid) {
            object[] results = this.invoke("giveup", new object[] {
                        appcode,
                        userid,
                        qtaskid});
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public system.iasyncresult begingiveup(string appcode, string userid, string qtaskid, system.asynccallback callback, object asyncstate) {
            return this.begininvoke("giveup", new object[] {
                        appcode,
                        userid,
                        qtaskid}, callback, asyncstate);
        }

        /// <remarks/>
        public bool endgiveup(system.iasyncresult asyncresult) {
            object[] results = this.endinvoke(asyncresult);
            return ((bool)(results[0]));
        }

        /// <remarks/>
        public void giveupasync(string appcode, string userid, string qtaskid) {
            this.giveupasync(appcode, userid, qtaskid, null);
        }

        /// <remarks/>
        public void giveupasync(string appcode, string userid, string qtaskid, object userstate) {
            if ((this.giveupoperationcompleted == null)) {
                this.giveupoperationcompleted = new system.threading.sendorpostcallback(this.ongiveupoperationcompleted);
            }
            this.invokeasync("giveup", new object[] {
                        appcode,
                        userid,
                        qtaskid}, this.giveupoperationcompleted, userstate);
        }

        private void ongiveupoperationcompleted(object arg) {
            if ((this.giveupcompleted != null)) {
                system.web.services.protocols.invokecompletedeventargs invokeargs = ((system.web.services.protocols.invokecompletedeventargs)(arg));
                this.giveupcompleted(this, new giveupcompletedeventargs(invokeargs.results, invokeargs.error, invokeargs.cancelled, invokeargs.userstate));
            }
        }

        /// <remarks/>
        [system.web.services.protocols.soapdocumentmethodattribute("http://tempuri.org/getquestiontasklist", requestnamespace="http://tempuri.org/", responsenamespace="http://tempuri.org/", use=system.web.services.description.soapbindinguse.literal, parameterstyle=system.web.services.protocols.soapparameterstyle.wrapped)]
        public system.data.dataset getquestiontasklist(string appcode, string userid) {
            object[] results = this.invoke("getquestiontasklist", new object[] {
                        appcode,
                        userid});
            return ((system.data.dataset)(results[0]));
        }

        /// <remarks/>
        public system.iasyncresult begingetquestiontasklist(string appcode, string userid, system.asynccallback callback, object asyncstate) {
            return this.begininvoke("getquestiontasklist", new object[] {
                        appcode,
                        userid}, callback, asyncstate);
        }

        /// <remarks/>
        public system.data.dataset endgetquestiontasklist(system.iasyncresult asyncresult) {
            object[] results = this.endinvoke(asyncresult);
            return ((system.data.dataset)(results[0]));
        }

        /// <remarks/>
        public void getquestiontasklistasync(string appcode, string userid) {
            this.getquestiontasklistasync(appcode, userid, null);
        }

        /// <remarks/>
        public void getquestiontasklistasync(string appcode, string userid, object userstate) {
            if ((this.getquestiontasklistoperationcompleted == null)) {
                this.getquestiontasklistoperationcompleted = new system.threading.sendorpostcallback(this.ongetquestiontasklistoperationcompleted);
            }
            this.invokeasync("getquestiontasklist", new object[] {
                        appcode,
                        userid}, this.getquestiontasklistoperationcompleted, userstate);
        }

        private void ongetquestiontasklistoperationcompleted(object arg) {
            if ((this.getquestiontasklistcompleted != null)) {
                system.web.services.protocols.invokecompletedeventargs invokeargs = ((system.web.services.protocols.invokecompletedeventargs)(arg));
                this.getquestiontasklistcompleted(this, new getquestiontasklistcompletedeventargs(invokeargs.results, invokeargs.error, invokeargs.cancelled, invokeargs.userstate));
            }
        }

        /// <remarks/>
        public new void cancelasync(object userstate) {
            base.cancelasync(userstate);
        }
    }

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    public delegate void getrecordnumcompletedeventhandler(object sender, getrecordnumcompletedeventargs e);

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    public partial class getrecordnumcompletedeventargs : system.componentmodel.asynccompletedeventargs {

        private object[] results;

        internal getrecordnumcompletedeventargs(object[] results, system.exception exception, bool cancelled, object userstate) :
                base(exception, cancelled, userstate) {
            this.results = results;
        }

        /// <remarks/>
        public int[] result {
            get {
                this.raiseexceptionifnecessary();
                return ((int[])(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    public delegate void getvotelistcompletedeventhandler(object sender, getvotelistcompletedeventargs e);

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    public partial class getvotelistcompletedeventargs : system.componentmodel.asynccompletedeventargs {

        private object[] results;

        internal getvotelistcompletedeventargs(object[] results, system.exception exception, bool cancelled, object userstate) :
                base(exception, cancelled, userstate) {
            this.results = results;
        }

        /// <remarks/>
        public system.data.dataset result {
            get {
                this.raiseexceptionifnecessary();
                return ((system.data.dataset)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    public delegate void votecompletedeventhandler(object sender, votecompletedeventargs e);

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    public partial class votecompletedeventargs : system.componentmodel.asynccompletedeventargs {

        private object[] results;

        internal votecompletedeventargs(object[] results, system.exception exception, bool cancelled, object userstate) :
                base(exception, cancelled, userstate) {
            this.results = results;
        }

        /// <remarks/>
        public bool result {
            get {
                this.raiseexceptionifnecessary();
                return ((bool)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    public delegate void giveupcompletedeventhandler(object sender, giveupcompletedeventargs e);

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    public partial class giveupcompletedeventargs : system.componentmodel.asynccompletedeventargs {

        private object[] results;

        internal giveupcompletedeventargs(object[] results, system.exception exception, bool cancelled, object userstate) :
                base(exception, cancelled, userstate) {
            this.results = results;
        }

        /// <remarks/>
        public bool result {
            get {
                this.raiseexceptionifnecessary();
                return ((bool)(this.results[0]));
            }
        }
    }

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    public delegate void getquestiontasklistcompletedeventhandler(object sender, getquestiontasklistcompletedeventargs e);

    /// <remarks/>
    [system.codedom.compiler.generatedcodeattribute("wsdl", "4.0.30319.1")]
    [system.diagnostics.debuggerstepthroughattribute()]
    [system.componentmodel.designercategoryattribute("code")]
    public partial class getquestiontasklistcompletedeventargs : system.componentmodel.asynccompletedeventargs {

        private object[] results;

        internal getquestiontasklistcompletedeventargs(object[] results, system.exception exception, bool cancelled, object userstate) :
                base(exception, cancelled, userstate) {
            this.results = results;
        }

        /// <remarks/>
        public system.data.dataset result {
            get {
                this.raiseexceptionifnecessary();
                return ((system.data.dataset)(this.results[0]));
            }
        }
    }
}

方法三:利用http 协议的get和post
这是最为灵活的方法。
复制代码 代码如下:

view code
using system;
using system.collections;
using system.io;
using system.net;
using system.text;
using system.xml;
using system.xml.serialization;
namespace bingosoft.ria.common
{
    /// <summary>
    ///  利用webrequest/webresponse进行webservice调用的类
    /// </summary>
    public class webservicecaller
    {
        #region tip:使用说明
        //webservices 应该支持get和post调用,在web.config应该增加以下代码
        //<webservices>
        //  <protocols>
        //    <add name="httpget"/>
        //    <add name="httppost"/>
        //  </protocols>
        //</webservices>
        //调用示例:
        //hashtable ht = new hashtable();  //hashtable 为webservice所需要的参数集
        //ht.add("str", "test");
        //ht.add("b", "true");
        //xmldocument xx = websvccaller.querysoapwebservice("http://localhost:81/service.asmx", "helloworld", ht);
        //messagebox.show(xx.outerxml);
        #endregion
        /// <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_x_x("soap", "body", "http://schemas.xmlsoap.org/soap/envelope/");
            xmlelement soapbody = doc.createelement("soap", "body", "http://schemas.xmlsoap.org/soap/envelope/");
            //xmlelement soapmethod = doc.createelement_x_x(methodname);
            xmlelement soapmethod = doc.createelement(methodname);
            soapmethod.setattribute("xmlns", xmlns);
            foreach (string k in pars.keys)
            {
                //xmlelement soappar = doc.createelement_x_x(k);
                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("&");
                }
                //sb.append(httputility.urlencode(k) + "=" + httputility.urlencode(pars[k].tostring()));
            }
            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();//缓存xmlnamespace,避免重复调用getnamespace
    }
}