微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net 调用webservice 总结

下面是webservice 代码

 

using System;@H_502_9@ using System.Collections.Generic;@H_502_9@ using System.Linq;@H_502_9@ using System.Web;@H_502_9@ using System.Web.Services;

namespace TestWebService@H_502_9@ {@H_502_9@     /// <summary>@H_502_9@     /// Service1 的摘要说明@H_502_9@     /// </summary>@H_502_9@     [WebService(Namespace = "http://tempuri.org/",Description="我的Web服务")]@H_502_9@     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]@H_502_9@     [System.ComponentModel.ToolBoxItem(false)]@H_502_9@     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。@H_502_9@     // [System.Web.Script.Services.ScriptService]@H_502_9@     public class TestWebService : System.Web.Services.WebService@H_502_9@     {

        [WebMethod]@H_502_9@         public string HelloWorld()@H_502_9@         {@H_502_9@             return "测试Hello World";@H_502_9@         }

        [WebMethod]@H_502_9@         public string test()@H_502_9@         {@H_502_9@             return "测试Test";@H_502_9@         }@H_502_9@       @H_502_9@         [WebMethod(CacheDuration = 60,Description = "测试")]@H_502_9@         public List<String> GetPersons()@H_502_9@         {@H_502_9@             List<String> list = new List<string>();@H_502_9@             list.Add("测试一");@H_502_9@             list.Add("测试二");@H_502_9@             list.Add("测试三");@H_502_9@             return list;@H_502_9@         } 

    }

}

 

 

动态调用示例:

方法一:

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

using System;@H_502_9@ using System.IO;@H_502_9@ using System.Collections.Generic;@H_502_9@ using System.Linq;@H_502_9@ using System.Collections;@H_502_9@ using System.Web;@H_502_9@ using System.Net;@H_502_9@ using System.Reflection;@H_502_9@ using System.CodeDom;@H_502_9@ using System.CodeDom.Compiler;@H_502_9@ using System.Web.Services;@H_502_9@ using System.Text;@H_502_9@ using System.Web.Services.Description;@H_502_9@ using System.Web.Services.Protocols;@H_502_9@ using System.Xml.Serialization;@H_502_9@ using System.Windows.Forms;

namespace ConsoleApplication1@H_502_9@ {@H_502_9@     class Program@H_502_9@     {@H_502_9@         static void Main(string[] args)@H_502_9@         {@H_502_9@             WebClient client = new WebClient();@H_502_9@             String url = "http://localhost:3182/Service1.asmx?WSDL";//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL@H_502_9@             Stream stream = client.OpenRead(url);@H_502_9@             ServiceDescription description = ServiceDescription.Read(stream);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();//创建客户端代理代理类。

            importer.ProtocolName = "Soap"; //指定访问协议。@H_502_9@             importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。@H_502_9@             importer.CodeGenerationoptions = CodeGenerationoptions.GenerateProperties | CodeGenerationoptions.GenerateNewAsync;

            importer.AddServiceDescription(description,null,null); //添加WSDL文档。

            CodeNamespace nmspace = new CodeNamespace(); //命名空间@H_502_9@             nmspace.Name = "TestWebService";@H_502_9@             CodeCompileUnit unit = new CodeCompileUnit();@H_502_9@             unit.Namespaces.Add(nmspace);

            ServiceDescriptionImportWarnings warning = importer.Import(nmspace,unit);@H_502_9@             CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CompilerParameters parameter = new CompilerParameters();@H_502_9@             parameter.GenerateExecutable = false;@H_502_9@             parameter.OutputAssembly = "MyTest.dll";//输出程序集的名称@H_502_9@             parameter.ReferencedAssemblies.Add("System.dll");@H_502_9@             parameter.ReferencedAssemblies.Add("System.XML.dll");@H_502_9@             parameter.ReferencedAssemblies.Add("System.Web.Services.dll");@H_502_9@             parameter.ReferencedAssemblies.Add("System.Data.dll");

            CompilerResults result = provider.CompileAssemblyFromDom(parameter,unit);@H_502_9@             if (result.Errors.HasErrors)@H_502_9@             {@H_502_9@                 // 显示编译错误信息@H_502_9@             }

            Assembly asm = Assembly.LoadFrom("MyTest.dll");//加载前面生成的程序集@H_502_9@             Type t = asm.GetType("TestWebService.TestWebService");

            object o = Activator.CreateInstance(t);@H_502_9@             MethodInfo method = t.getmethod("GetPersons");//GetPersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下

            String[] item = (String[])method.Invoke(o,null);@H_502_9@             //注:method.Invoke(o,null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o,null)转一下就行了,method.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的@H_502_9@             foreach (string str in item)@H_502_9@                 Console.WriteLine(str);

            //上面是根据WebService地址,模似生成一个代理类,如果你想看看生成代码文件是什么样子,可以用以下代码保存下来,认是保存在bin目录下面@H_502_9@             TextWriter writer = File.CreateText("MyTest.cs"); @H_502_9@             provider.GenerateCodeFromCompileUnit(unit,writer,null);@H_502_9@             writer.Flush();@H_502_9@             writer.Close();@H_502_9@         } @H_502_9@     }@H_502_9@ }

在网上找了一个更为详细的

http://www.voidcn.com/article/p-kthiqwfl-qo.html

 

 

方法二:利用 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 一个出来后,可以进行调用

   贴出由命令行编译出来的代码

//------------------------------------------------------------------------------@H_502_9@ // <auto-generated>@H_502_9@ //     此代码由工具生成。@H_502_9@ //     运行时版本:4.0.30319.225@H_502_9@ //@H_502_9@ //     对此文件的更改可能会导致不正确的行为,并且如果@H_502_9@ //     重新生成代码,这些更改将会丢失。@H_502_9@ // </auto-generated>@H_502_9@ //------------------------------------------------------------------------------

// @H_502_9@ // 此源代码由 wsdl 自动生成,Version=4.0.30319.1。@H_502_9@ // @H_502_9@ namespace Bingosoft.Module.SurveyQuestionnaire.DAL {@H_502_9@     using System;@H_502_9@     using System.Diagnostics;@H_502_9@     using System.Xml.Serialization;@H_502_9@     using System.ComponentModel;@H_502_9@     using System.Web.Services.Protocols;@H_502_9@     using System.Web.Services;@H_502_9@     using System.Data;@H_502_9@     @H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     [System.Web.Services.WebServiceBindingAttribute(Name="WebserviceForILookSoap",Namespace="http://tempuri.org/")]@H_502_9@     public partial class WebserviceForILook : System.Web.Services.Protocols.soapHttpClientProtocol {@H_502_9@         @H_502_9@         private System.Threading.SendOrPostCallback GetRecordNumOperationCompleted;@H_502_9@         @H_502_9@         private System.Threading.SendOrPostCallback GetVoteListOperationCompleted;@H_502_9@         @H_502_9@         private System.Threading.SendOrPostCallback VoteOperationCompleted;@H_502_9@         @H_502_9@         private System.Threading.SendOrPostCallback GiveUpOperationCompleted;@H_502_9@         @H_502_9@         private System.Threading.SendOrPostCallback GetQuestionTaskListOperationCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public WebserviceForILook() {@H_502_9@             this.Url = "http://st1.services.gmcc.net/qnaire/Services/WebserviceForILook.asmx";@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public event GetRecordNumCompletedEventHandler GetRecordNumCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public event GetVoteListCompletedEventHandler GetVoteListCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public event VoteCompletedEventHandler VoteCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public event GiveUpCompletedEventHandler GiveUpCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public event GetQuestionTaskListCompletedEventHandler GetQuestionTaskListCompleted;@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         [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)]@H_502_9@         public int[] GetRecordNum(string appcode,string userID) {@H_502_9@             object[] results = this.Invoke("GetRecordNum",new object[] {@H_502_9@                         appcode,@H_502_9@                         userID});@H_502_9@             return ((int[])(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.IAsyncResult BeginGetRecordNum(string appcode,string userID,System.AsyncCallback callback,object asyncState) {@H_502_9@             return this.BeginInvoke("GetRecordNum",@H_502_9@                         userID},callback,asyncState);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public int[] EndGetRecordNum(System.IAsyncResult asyncResult) {@H_502_9@             object[] results = this.EndInvoke(asyncResult);@H_502_9@             return ((int[])(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetRecordNumAsync(string appcode,string userID) {@H_502_9@             this.GetRecordNumAsync(appcode,userID,null);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetRecordNumAsync(string appcode,object userState) {@H_502_9@             if ((this.GetRecordNumOperationCompleted == null)) {@H_502_9@                 this.GetRecordNumOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRecordNumOperationCompleted);@H_502_9@             }@H_502_9@             this.InvokeAsync("GetRecordNum",this.GetRecordNumOperationCompleted,userState);@H_502_9@         }@H_502_9@         @H_502_9@         private void OnGetRecordNumOperationCompleted(object arg) {@H_502_9@             if ((this.GetRecordNumCompleted != null)) {@H_502_9@                 System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));@H_502_9@                 this.GetRecordNumCompleted(this,new GetRecordNumCompletedEventArgs(invokeArgs.Results,invokeArgs.Error,invokeArgs.Cancelled,invokeArgs.UserState));@H_502_9@             }@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         [System.Web.Services.Protocols.soapDocumentMethodAttribute("http://tempuri.org/GetVoteList",ParameterStyle=System.Web.Services.Protocols.soapParameterStyle.Wrapped)]@H_502_9@         public System.Data.DataSet GetVoteList(string appcode,string userID) {@H_502_9@             object[] results = this.Invoke("GetVoteList",@H_502_9@                         userID});@H_502_9@             return ((System.Data.DataSet)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.IAsyncResult BeginGetVoteList(string appcode,object asyncState) {@H_502_9@             return this.BeginInvoke("GetVoteList",asyncState);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.Data.DataSet EndGetVoteList(System.IAsyncResult asyncResult) {@H_502_9@             object[] results = this.EndInvoke(asyncResult);@H_502_9@             return ((System.Data.DataSet)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetVoteListAsync(string appcode,string userID) {@H_502_9@             this.GetVoteListAsync(appcode,null);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetVoteListAsync(string appcode,object userState) {@H_502_9@             if ((this.GetVoteListOperationCompleted == null)) {@H_502_9@                 this.GetVoteListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetVoteListOperationCompleted);@H_502_9@             }@H_502_9@             this.InvokeAsync("GetVoteList",this.GetVoteListOperationCompleted,userState);@H_502_9@         }@H_502_9@         @H_502_9@         private void OnGetVoteListOperationCompleted(object arg) {@H_502_9@             if ((this.GetVoteListCompleted != null)) {@H_502_9@                 System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));@H_502_9@                 this.GetVoteListCompleted(this,new GetVoteListCompletedEventArgs(invokeArgs.Results,invokeArgs.UserState));@H_502_9@             }@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         [System.Web.Services.Protocols.soapDocumentMethodAttribute("http://tempuri.org/Vote",ParameterStyle=System.Web.Services.Protocols.soapParameterStyle.Wrapped)]@H_502_9@         public bool Vote(string appcode,string qTaskID,string answer) {@H_502_9@             object[] results = this.Invoke("Vote",@H_502_9@                         userID,@H_502_9@                         qTaskID,@H_502_9@                         answer});@H_502_9@             return ((bool)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.IAsyncResult BeginVote(string appcode,string answer,object asyncState) {@H_502_9@             return this.BeginInvoke("Vote",@H_502_9@                         answer},asyncState);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public bool EndVote(System.IAsyncResult asyncResult) {@H_502_9@             object[] results = this.EndInvoke(asyncResult);@H_502_9@             return ((bool)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void VoteAsync(string appcode,string answer) {@H_502_9@             this.VoteAsync(appcode,qTaskID,answer,null);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void VoteAsync(string appcode,object userState) {@H_502_9@             if ((this.VoteOperationCompleted == null)) {@H_502_9@                 this.VoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnVoteOperationCompleted);@H_502_9@             }@H_502_9@             this.InvokeAsync("Vote",this.VoteOperationCompleted,userState);@H_502_9@         }@H_502_9@         @H_502_9@         private void OnVoteOperationCompleted(object arg) {@H_502_9@             if ((this.VoteCompleted != null)) {@H_502_9@                 System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));@H_502_9@                 this.VoteCompleted(this,new VoteCompletedEventArgs(invokeArgs.Results,invokeArgs.UserState));@H_502_9@             }@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         [System.Web.Services.Protocols.soapDocumentMethodAttribute("http://tempuri.org/GiveUp",ParameterStyle=System.Web.Services.Protocols.soapParameterStyle.Wrapped)]@H_502_9@         public bool GiveUp(string appcode,string qTaskID) {@H_502_9@             object[] results = this.Invoke("GiveUp",@H_502_9@                         qTaskID});@H_502_9@             return ((bool)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.IAsyncResult BeginGiveUp(string appcode,object asyncState) {@H_502_9@             return this.BeginInvoke("GiveUp",@H_502_9@                         qTaskID},asyncState);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public bool EndGiveUp(System.IAsyncResult asyncResult) {@H_502_9@             object[] results = this.EndInvoke(asyncResult);@H_502_9@             return ((bool)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GiveUpAsync(string appcode,string qTaskID) {@H_502_9@             this.GiveUpAsync(appcode,null);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GiveUpAsync(string appcode,object userState) {@H_502_9@             if ((this.GiveUpOperationCompleted == null)) {@H_502_9@                 this.GiveUpOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGiveUpOperationCompleted);@H_502_9@             }@H_502_9@             this.InvokeAsync("GiveUp",this.GiveUpOperationCompleted,userState);@H_502_9@         }@H_502_9@         @H_502_9@         private void OnGiveUpOperationCompleted(object arg) {@H_502_9@             if ((this.GiveUpCompleted != null)) {@H_502_9@                 System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));@H_502_9@                 this.GiveUpCompleted(this,new GiveUpCompletedEventArgs(invokeArgs.Results,invokeArgs.UserState));@H_502_9@             }@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         [System.Web.Services.Protocols.soapDocumentMethodAttribute("http://tempuri.org/GetQuestionTaskList",ParameterStyle=System.Web.Services.Protocols.soapParameterStyle.Wrapped)]@H_502_9@         public System.Data.DataSet GetQuestionTaskList(string appcode,string userID) {@H_502_9@             object[] results = this.Invoke("GetQuestionTaskList",@H_502_9@                         userID});@H_502_9@             return ((System.Data.DataSet)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.IAsyncResult BeginGetQuestionTaskList(string appcode,object asyncState) {@H_502_9@             return this.BeginInvoke("GetQuestionTaskList",asyncState);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.Data.DataSet EndGetQuestionTaskList(System.IAsyncResult asyncResult) {@H_502_9@             object[] results = this.EndInvoke(asyncResult);@H_502_9@             return ((System.Data.DataSet)(results[0]));@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetQuestionTaskListAsync(string appcode,string userID) {@H_502_9@             this.GetQuestionTaskListAsync(appcode,null);@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public void GetQuestionTaskListAsync(string appcode,object userState) {@H_502_9@             if ((this.GetQuestionTaskListOperationCompleted == null)) {@H_502_9@                 this.GetQuestionTaskListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetQuestionTaskListOperationCompleted);@H_502_9@             }@H_502_9@             this.InvokeAsync("GetQuestionTaskList",this.GetQuestionTaskListOperationCompleted,userState);@H_502_9@         }@H_502_9@         @H_502_9@         private void OnGetQuestionTaskListOperationCompleted(object arg) {@H_502_9@             if ((this.GetQuestionTaskListCompleted != null)) {@H_502_9@                 System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));@H_502_9@                 this.GetQuestionTaskListCompleted(this,new GetQuestionTaskListCompletedEventArgs(invokeArgs.Results,invokeArgs.UserState));@H_502_9@             }@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public new void CancelAsync(object userState) {@H_502_9@             base.CancelAsync(userState);@H_502_9@         }@H_502_9@     }@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     public delegate void GetRecordNumCompletedEventHandler(object sender,GetRecordNumCompletedEventArgs e);@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     public partial class GetRecordNumCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {@H_502_9@         @H_502_9@         private object[] results;@H_502_9@         @H_502_9@         internal GetRecordNumCompletedEventArgs(object[] results,System.Exception exception,bool cancelled,object userState) : @H_502_9@                 base(exception,cancelled,userState) {@H_502_9@             this.results = results;@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public int[] Result {@H_502_9@             get {@H_502_9@                 this.RaiseExceptionIfNecessary();@H_502_9@                 return ((int[])(this.results[0]));@H_502_9@             }@H_502_9@         }@H_502_9@     }@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     public delegate void GetVoteListCompletedEventHandler(object sender,GetVoteListCompletedEventArgs e);@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     public partial class GetVoteListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {@H_502_9@         @H_502_9@         private object[] results;@H_502_9@         @H_502_9@         internal GetVoteListCompletedEventArgs(object[] results,userState) {@H_502_9@             this.results = results;@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.Data.DataSet Result {@H_502_9@             get {@H_502_9@                 this.RaiseExceptionIfNecessary();@H_502_9@                 return ((System.Data.DataSet)(this.results[0]));@H_502_9@             }@H_502_9@         }@H_502_9@     }@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     public delegate void VoteCompletedEventHandler(object sender,VoteCompletedEventArgs e);@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     public partial class VoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {@H_502_9@         @H_502_9@         private object[] results;@H_502_9@         @H_502_9@         internal VoteCompletedEventArgs(object[] results,userState) {@H_502_9@             this.results = results;@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public bool Result {@H_502_9@             get {@H_502_9@                 this.RaiseExceptionIfNecessary();@H_502_9@                 return ((bool)(this.results[0]));@H_502_9@             }@H_502_9@         }@H_502_9@     }@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     public delegate void GiveUpCompletedEventHandler(object sender,GiveUpCompletedEventArgs e);@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     public partial class GiveUpCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {@H_502_9@         @H_502_9@         private object[] results;@H_502_9@         @H_502_9@         internal GiveUpCompletedEventArgs(object[] results,"4.0.30319.1")]@H_502_9@     public delegate void GetQuestionTaskListCompletedEventHandler(object sender,GetQuestionTaskListCompletedEventArgs e);@H_502_9@     @H_502_9@     /// <remarks/>@H_502_9@     [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl","4.0.30319.1")]@H_502_9@     [System.Diagnostics.DebuggerStepThroughAttribute()]@H_502_9@     [System.ComponentModel.DesignerCategoryAttribute("code")]@H_502_9@     public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {@H_502_9@         @H_502_9@         private object[] results;@H_502_9@         @H_502_9@         internal GetQuestionTaskListCompletedEventArgs(object[] results,userState) {@H_502_9@             this.results = results;@H_502_9@         }@H_502_9@         @H_502_9@         /// <remarks/>@H_502_9@         public System.Data.DataSet Result {@H_502_9@             get {@H_502_9@                 this.RaiseExceptionIfNecessary();@H_502_9@                 return ((System.Data.DataSet)(this.results[0]));@H_502_9@             }@H_502_9@         }@H_502_9@     }@H_502_9@ }

更为详细的可以参见:http://www.voidcn.com/article/p-drlofvnv-dn.html

 

方法三:利用http 协议的get  和post

这是最为灵活的方法

using System;@H_502_9@ using System.Collections;@H_502_9@ using System.IO;@H_502_9@ using System.Net;@H_502_9@ using System.Text;@H_502_9@ using System.Xml;@H_502_9@ using System.Xml.Serialization;@H_502_9@ namespace Bingosoft.RIA.Common@H_502_9@ {@H_502_9@     /// <summary>@H_502_9@     ///  利用WebRequest/WebResponse进行WebService调用的类@H_502_9@     /// </summary>@H_502_9@     public class WebServiceCaller@H_502_9@     {@H_502_9@         #region Tip:使用说明@H_502_9@         //webServices 应该支持Get和Post调用,在web.config应该增加以下代码@H_502_9@         //<webServices>@H_502_9@         //  <protocols>@H_502_9@         //    <add name="HttpGet"/>@H_502_9@         //    <add name="HttpPost"/>@H_502_9@         //  </protocols>@H_502_9@         //</webServices>

        //调用示例:@H_502_9@         //Hashtable ht = new Hashtable();  //Hashtable 为webservice所需要的参数集@H_502_9@         //ht.Add("str","test");@H_502_9@         //ht.Add("b","true");@H_502_9@         //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx","HelloWorld",ht);@H_502_9@         //MessageBox.Show(xx.OuterXml);@H_502_9@         #endregion

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

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

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

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

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

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

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

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

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

        private static String ParsToString(Hashtable Pars)@H_502_9@         {@H_502_9@             StringBuilder sb = new StringBuilder();@H_502_9@             foreach (string k in Pars.Keys)@H_502_9@             {@H_502_9@                 if (sb.Length > 0)@H_502_9@                 {@H_502_9@                     sb.Append("&");@H_502_9@                 }@H_502_9@                 //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));@H_502_9@             }@H_502_9@             return sb.ToString();@H_502_9@         }

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

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

        private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace     } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐