最近做一个项目,由于是在别人框架里开发app,导致了很多限制,其中一个就是不能直接引用webservice 。

我们都知道,调用webserivice 最简单的方法就是在 "引用"  那里点击右键,然后选择"引用web服务",再输入服务地址。

确定后,会生成一个app.config 里面就会自动生成了一些配置信息。

现在正在做的这个项目就不能这么干。后来经过一番搜索,就找出另外几种动态调用webservice 的方法。

废话少说,下面是webservice 代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Services;
  6.  
  7. namespace TestWebService
  8. {
  9. /// <summary>
  10. /// Service1 的摘要说明
  11. /// </summary>
  12. [WebService(Namespace = "http://tempuri.org/",Description="我的Web服务")]
  13. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  14. [System.ComponentModel.ToolboxItem(false)]
  15. // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
  16. // [System.Web.Script.Services.ScriptService]
  17. public class TestWebService : System.Web.Services.WebService
  18. {
  19.  
  20. [WebMethod]
  21. public string HelloWorld()
  22. {
  23. return "测试Hello World";
  24. }
  25.  
  26. [WebMethod]
  27. public string Test()
  28. {
  29. return "测试Test";
  30. }
  31.  
  32. [WebMethod(CacheDuration = ,Description = "测试")]
  33. public List<String> GetPersons()
  34. {
  35. List<String> list = new List<string>();
  36. list.Add("测试一");
  37. list.Add("测试二");
  38. list.Add("测试三");
  39. return list;
  40. }
  41.  
  42. }
  43.  
  44. }

动态调用示例:

方法一:

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

  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Collections;
  6. using System.Web;
  7. using System.Net;
  8. using System.Reflection;
  9. using System.CodeDom;
  10. using System.CodeDom.Compiler;
  11. using System.Web.Services;
  12. using System.Text;
  13. using System.Web.Services.Description;
  14. using System.Web.Services.Protocols;
  15. using System.Xml.Serialization;
  16. using System.Windows.Forms;
  17.  
  18. namespace ConsoleApplication1
  19. {
  20. class Program
  21. {
  22. static void Main(string[] args)
  23. {
  24. WebClient client = new WebClient();
  25. String url = "http://localhost:3182/Service1.asmx?WSDL";//这个地址可以写在Config文件里面,这里取出来就行了.在原地址后面加上: ?WSDL
  26. Stream stream = client.OpenRead(url);
  27. ServiceDescription description = ServiceDescription.Read(stream);
  28.  
  29. ServiceDescriptionImporter importer = new ServiceDescriptionImporter();//创建客户端代理代理类。
  30.  
  31. importer.ProtocolName = "Soap"; //指定访问协议。
  32. importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。
  33. importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
  34.  
  35. importer.AddServiceDescription(description, null, null); //添加WSDL文档。
  36.  
  37. CodeNamespace nmspace = new CodeNamespace(); //命名空间
  38. nmspace.Name = "TestWebService";
  39. CodeCompileUnit unit = new CodeCompileUnit();
  40. unit.Namespaces.Add(nmspace);
  41.  
  42. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
  43. CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
  44.  
  45. CompilerParameters parameter = new CompilerParameters();
  46. parameter.GenerateExecutable = false;
  47. parameter.OutputAssembly = "MyTest.dll";//输出程序集的名称
  48. parameter.ReferencedAssemblies.Add("System.dll");
  49. parameter.ReferencedAssemblies.Add("System.XML.dll");
  50. parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
  51. parameter.ReferencedAssemblies.Add("System.Data.dll");
  52.  
  53. CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
  54. if (result.Errors.HasErrors)
  55. {
  56. // 显示编译错误信息
  57. }
  58.  
  59. Assembly asm = Assembly.LoadFrom("MyTest.dll");//加载前面生成的程序集
  60. Type t = asm.GetType("TestWebService.TestWebService");
  61.  
  62. object o = Activator.CreateInstance(t);
  63. MethodInfo method = t.GetMethod("GetPersons");//GetPersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下
  64.  
  65. String[] item = (String[])method.Invoke(o, null);
  66. //注:method.Invoke(o, null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o, null)转一下就行了,method.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的
  67. foreach (string str in item)
  68. Console.WriteLine(str);
  69.  
  70. //上面是根据WebService地址,模似生成一个代理类,如果你想看看生成的代码文件是什么样子,可以用以下代码保存下来,默认是保存在bin目录下面
  71. TextWriter writer = File.CreateText("MyTest.cs");
  72. provider.GenerateCodeFromCompileUnit(unit, writer, null);
  73. writer.Flush();
  74. writer.Close();
  75. }
  76. }
  77. }

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

http://blog.csdn.net/ysq5202121/article/details/6942813

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

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

  1. //------------------------------------------------------------------------------
  2. // <auto-generated>
  3. // 此代码由工具生成。
  4. // 运行时版本:4.0.30319.225
  5. //
  6. // 对此文件的更改可能会导致不正确的行为,并且如果
  7. // 重新生成代码,这些更改将会丢失。
  8. // </auto-generated>
  9. //------------------------------------------------------------------------------
  10.  
  11. //
  12. // 此源代码由 wsdl 自动生成, Version=4.0.30319.1。
  13. //
  14. namespace Bingosoft.Module.SurveyQuestionnaire.DAL {
  15. using System;
  16. using System.Diagnostics;
  17. using System.Xml.Serialization;
  18. using System.ComponentModel;
  19. using System.Web.Services.Protocols;
  20. using System.Web.Services;
  21. using System.Data;
  22.  
  23. /// <remarks/>
  24. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  25. [System.Diagnostics.DebuggerStepThroughAttribute()]
  26. [System.ComponentModel.DesignerCategoryAttribute("code")]
  27. [System.Web.Services.WebServiceBindingAttribute(Name="WebserviceForILookSoap", Namespace="http://tempuri.org/")]
  28. public partial class WebserviceForILook : System.Web.Services.Protocols.SoapHttpClientProtocol {
  29.  
  30. private System.Threading.SendOrPostCallback GetRecordNumOperationCompleted;
  31.  
  32. private System.Threading.SendOrPostCallback GetVoteListOperationCompleted;
  33.  
  34. private System.Threading.SendOrPostCallback VoteOperationCompleted;
  35.  
  36. private System.Threading.SendOrPostCallback GiveUpOperationCompleted;
  37.  
  38. private System.Threading.SendOrPostCallback GetQuestionTaskListOperationCompleted;
  39.  
  40. /// <remarks/>
  41. public WebserviceForILook() {
  42. this.Url = "http://st1.services.gmcc.net/qnaire/Services/WebserviceForILook.asmx";
  43. }
  44.  
  45. /// <remarks/>
  46. public event GetRecordNumCompletedEventHandler GetRecordNumCompleted;
  47.  
  48. /// <remarks/>
  49. public event GetVoteListCompletedEventHandler GetVoteListCompleted;
  50.  
  51. /// <remarks/>
  52. public event VoteCompletedEventHandler VoteCompleted;
  53.  
  54. /// <remarks/>
  55. public event GiveUpCompletedEventHandler GiveUpCompleted;
  56.  
  57. /// <remarks/>
  58. public event GetQuestionTaskListCompletedEventHandler GetQuestionTaskListCompleted;
  59.  
  60. /// <remarks/>
  61. [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)]
  62. public int[] GetRecordNum(string appcode, string userID) {
  63. object[] results = this.Invoke("GetRecordNum", new object[] {
  64. appcode,
  65. userID});
  66. return ((int[])(results[]));
  67. }
  68.  
  69. /// <remarks/>
  70. public System.IAsyncResult BeginGetRecordNum(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
  71. return this.BeginInvoke("GetRecordNum", new object[] {
  72. appcode,
  73. userID}, callback, asyncState);
  74. }
  75.  
  76. /// <remarks/>
  77. public int[] EndGetRecordNum(System.IAsyncResult asyncResult) {
  78. object[] results = this.EndInvoke(asyncResult);
  79. return ((int[])(results[]));
  80. }
  81.  
  82. /// <remarks/>
  83. public void GetRecordNumAsync(string appcode, string userID) {
  84. this.GetRecordNumAsync(appcode, userID, null);
  85. }
  86.  
  87. /// <remarks/>
  88. public void GetRecordNumAsync(string appcode, string userID, object userState) {
  89. if ((this.GetRecordNumOperationCompleted == null)) {
  90. this.GetRecordNumOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetRecordNumOperationCompleted);
  91. }
  92. this.InvokeAsync("GetRecordNum", new object[] {
  93. appcode,
  94. userID}, this.GetRecordNumOperationCompleted, userState);
  95. }
  96.  
  97. private void OnGetRecordNumOperationCompleted(object arg) {
  98. if ((this.GetRecordNumCompleted != null)) {
  99. System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
  100. this.GetRecordNumCompleted(this, new GetRecordNumCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  101. }
  102. }
  103.  
  104. /// <remarks/>
  105. [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)]
  106. public System.Data.DataSet GetVoteList(string appcode, string userID) {
  107. object[] results = this.Invoke("GetVoteList", new object[] {
  108. appcode,
  109. userID});
  110. return ((System.Data.DataSet)(results[]));
  111. }
  112.  
  113. /// <remarks/>
  114. public System.IAsyncResult BeginGetVoteList(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
  115. return this.BeginInvoke("GetVoteList", new object[] {
  116. appcode,
  117. userID}, callback, asyncState);
  118. }
  119.  
  120. /// <remarks/>
  121. public System.Data.DataSet EndGetVoteList(System.IAsyncResult asyncResult) {
  122. object[] results = this.EndInvoke(asyncResult);
  123. return ((System.Data.DataSet)(results[]));
  124. }
  125.  
  126. /// <remarks/>
  127. public void GetVoteListAsync(string appcode, string userID) {
  128. this.GetVoteListAsync(appcode, userID, null);
  129. }
  130.  
  131. /// <remarks/>
  132. public void GetVoteListAsync(string appcode, string userID, object userState) {
  133. if ((this.GetVoteListOperationCompleted == null)) {
  134. this.GetVoteListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetVoteListOperationCompleted);
  135. }
  136. this.InvokeAsync("GetVoteList", new object[] {
  137. appcode,
  138. userID}, this.GetVoteListOperationCompleted, userState);
  139. }
  140.  
  141. private void OnGetVoteListOperationCompleted(object arg) {
  142. if ((this.GetVoteListCompleted != null)) {
  143. System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
  144. this.GetVoteListCompleted(this, new GetVoteListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  145. }
  146. }
  147.  
  148. /// <remarks/>
  149. [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)]
  150. public bool Vote(string appcode, string userID, string qTaskID, string answer) {
  151. object[] results = this.Invoke("Vote", new object[] {
  152. appcode,
  153. userID,
  154. qTaskID,
  155. answer});
  156. return ((bool)(results[]));
  157. }
  158.  
  159. /// <remarks/>
  160. public System.IAsyncResult BeginVote(string appcode, string userID, string qTaskID, string answer, System.AsyncCallback callback, object asyncState) {
  161. return this.BeginInvoke("Vote", new object[] {
  162. appcode,
  163. userID,
  164. qTaskID,
  165. answer}, callback, asyncState);
  166. }
  167.  
  168. /// <remarks/>
  169. public bool EndVote(System.IAsyncResult asyncResult) {
  170. object[] results = this.EndInvoke(asyncResult);
  171. return ((bool)(results[]));
  172. }
  173.  
  174. /// <remarks/>
  175. public void VoteAsync(string appcode, string userID, string qTaskID, string answer) {
  176. this.VoteAsync(appcode, userID, qTaskID, answer, null);
  177. }
  178.  
  179. /// <remarks/>
  180. public void VoteAsync(string appcode, string userID, string qTaskID, string answer, object userState) {
  181. if ((this.VoteOperationCompleted == null)) {
  182. this.VoteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnVoteOperationCompleted);
  183. }
  184. this.InvokeAsync("Vote", new object[] {
  185. appcode,
  186. userID,
  187. qTaskID,
  188. answer}, this.VoteOperationCompleted, userState);
  189. }
  190.  
  191. private void OnVoteOperationCompleted(object arg) {
  192. if ((this.VoteCompleted != null)) {
  193. System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
  194. this.VoteCompleted(this, new VoteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  195. }
  196. }
  197.  
  198. /// <remarks/>
  199. [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)]
  200. public bool GiveUp(string appcode, string userID, string qTaskID) {
  201. object[] results = this.Invoke("GiveUp", new object[] {
  202. appcode,
  203. userID,
  204. qTaskID});
  205. return ((bool)(results[]));
  206. }
  207.  
  208. /// <remarks/>
  209. public System.IAsyncResult BeginGiveUp(string appcode, string userID, string qTaskID, System.AsyncCallback callback, object asyncState) {
  210. return this.BeginInvoke("GiveUp", new object[] {
  211. appcode,
  212. userID,
  213. qTaskID}, callback, asyncState);
  214. }
  215.  
  216. /// <remarks/>
  217. public bool EndGiveUp(System.IAsyncResult asyncResult) {
  218. object[] results = this.EndInvoke(asyncResult);
  219. return ((bool)(results[]));
  220. }
  221.  
  222. /// <remarks/>
  223. public void GiveUpAsync(string appcode, string userID, string qTaskID) {
  224. this.GiveUpAsync(appcode, userID, qTaskID, null);
  225. }
  226.  
  227. /// <remarks/>
  228. public void GiveUpAsync(string appcode, string userID, string qTaskID, object userState) {
  229. if ((this.GiveUpOperationCompleted == null)) {
  230. this.GiveUpOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGiveUpOperationCompleted);
  231. }
  232. this.InvokeAsync("GiveUp", new object[] {
  233. appcode,
  234. userID,
  235. qTaskID}, this.GiveUpOperationCompleted, userState);
  236. }
  237.  
  238. private void OnGiveUpOperationCompleted(object arg) {
  239. if ((this.GiveUpCompleted != null)) {
  240. System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
  241. this.GiveUpCompleted(this, new GiveUpCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  242. }
  243. }
  244.  
  245. /// <remarks/>
  246. [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)]
  247. public System.Data.DataSet GetQuestionTaskList(string appcode, string userID) {
  248. object[] results = this.Invoke("GetQuestionTaskList", new object[] {
  249. appcode,
  250. userID});
  251. return ((System.Data.DataSet)(results[]));
  252. }
  253.  
  254. /// <remarks/>
  255. public System.IAsyncResult BeginGetQuestionTaskList(string appcode, string userID, System.AsyncCallback callback, object asyncState) {
  256. return this.BeginInvoke("GetQuestionTaskList", new object[] {
  257. appcode,
  258. userID}, callback, asyncState);
  259. }
  260.  
  261. /// <remarks/>
  262. public System.Data.DataSet EndGetQuestionTaskList(System.IAsyncResult asyncResult) {
  263. object[] results = this.EndInvoke(asyncResult);
  264. return ((System.Data.DataSet)(results[]));
  265. }
  266.  
  267. /// <remarks/>
  268. public void GetQuestionTaskListAsync(string appcode, string userID) {
  269. this.GetQuestionTaskListAsync(appcode, userID, null);
  270. }
  271.  
  272. /// <remarks/>
  273. public void GetQuestionTaskListAsync(string appcode, string userID, object userState) {
  274. if ((this.GetQuestionTaskListOperationCompleted == null)) {
  275. this.GetQuestionTaskListOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetQuestionTaskListOperationCompleted);
  276. }
  277. this.InvokeAsync("GetQuestionTaskList", new object[] {
  278. appcode,
  279. userID}, this.GetQuestionTaskListOperationCompleted, userState);
  280. }
  281.  
  282. private void OnGetQuestionTaskListOperationCompleted(object arg) {
  283. if ((this.GetQuestionTaskListCompleted != null)) {
  284. System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
  285. this.GetQuestionTaskListCompleted(this, new GetQuestionTaskListCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
  286. }
  287. }
  288.  
  289. /// <remarks/>
  290. public new void CancelAsync(object userState) {
  291. base.CancelAsync(userState);
  292. }
  293. }
  294.  
  295. /// <remarks/>
  296. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  297. public delegate void GetRecordNumCompletedEventHandler(object sender, GetRecordNumCompletedEventArgs e);
  298.  
  299. /// <remarks/>
  300. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  301. [System.Diagnostics.DebuggerStepThroughAttribute()]
  302. [System.ComponentModel.DesignerCategoryAttribute("code")]
  303. public partial class GetRecordNumCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
  304.  
  305. private object[] results;
  306.  
  307. internal GetRecordNumCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
  308. base(exception, cancelled, userState) {
  309. this.results = results;
  310. }
  311.  
  312. /// <remarks/>
  313. public int[] Result {
  314. get {
  315. this.RaiseExceptionIfNecessary();
  316. return ((int[])(this.results[]));
  317. }
  318. }
  319. }
  320.  
  321. /// <remarks/>
  322. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  323. public delegate void GetVoteListCompletedEventHandler(object sender, GetVoteListCompletedEventArgs e);
  324.  
  325. /// <remarks/>
  326. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  327. [System.Diagnostics.DebuggerStepThroughAttribute()]
  328. [System.ComponentModel.DesignerCategoryAttribute("code")]
  329. public partial class GetVoteListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
  330.  
  331. private object[] results;
  332.  
  333. internal GetVoteListCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
  334. base(exception, cancelled, userState) {
  335. this.results = results;
  336. }
  337.  
  338. /// <remarks/>
  339. public System.Data.DataSet Result {
  340. get {
  341. this.RaiseExceptionIfNecessary();
  342. return ((System.Data.DataSet)(this.results[]));
  343. }
  344. }
  345. }
  346.  
  347. /// <remarks/>
  348. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  349. public delegate void VoteCompletedEventHandler(object sender, VoteCompletedEventArgs e);
  350.  
  351. /// <remarks/>
  352. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  353. [System.Diagnostics.DebuggerStepThroughAttribute()]
  354. [System.ComponentModel.DesignerCategoryAttribute("code")]
  355. public partial class VoteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
  356.  
  357. private object[] results;
  358.  
  359. internal VoteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
  360. base(exception, cancelled, userState) {
  361. this.results = results;
  362. }
  363.  
  364. /// <remarks/>
  365. public bool Result {
  366. get {
  367. this.RaiseExceptionIfNecessary();
  368. return ((bool)(this.results[]));
  369. }
  370. }
  371. }
  372.  
  373. /// <remarks/>
  374. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  375. public delegate void GiveUpCompletedEventHandler(object sender, GiveUpCompletedEventArgs e);
  376.  
  377. /// <remarks/>
  378. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  379. [System.Diagnostics.DebuggerStepThroughAttribute()]
  380. [System.ComponentModel.DesignerCategoryAttribute("code")]
  381. public partial class GiveUpCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
  382.  
  383. private object[] results;
  384.  
  385. internal GiveUpCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
  386. base(exception, cancelled, userState) {
  387. this.results = results;
  388. }
  389.  
  390. /// <remarks/>
  391. public bool Result {
  392. get {
  393. this.RaiseExceptionIfNecessary();
  394. return ((bool)(this.results[]));
  395. }
  396. }
  397. }
  398.  
  399. /// <remarks/>
  400. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  401. public delegate void GetQuestionTaskListCompletedEventHandler(object sender, GetQuestionTaskListCompletedEventArgs e);
  402.  
  403. /// <remarks/>
  404. [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.0.30319.1")]
  405. [System.Diagnostics.DebuggerStepThroughAttribute()]
  406. [System.ComponentModel.DesignerCategoryAttribute("code")]
  407. public partial class GetQuestionTaskListCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
  408.  
  409. private object[] results;
  410.  
  411. internal GetQuestionTaskListCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) :
  412. base(exception, cancelled, userState) {
  413. this.results = results;
  414. }
  415.  
  416. /// <remarks/>
  417. public System.Data.DataSet Result {
  418. get {
  419. this.RaiseExceptionIfNecessary();
  420. return ((System.Data.DataSet)(this.results[]));
  421. }
  422. }
  423. }
  424. }

更为详细的可以参见:http://blog.csdn.net/slimboy123/article/details/4344914

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

这是最为灵活的方法。

  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using System.Xml;
  7. using System.Xml.Serialization;
  8. namespace Bingosoft.RIA.Common
  9. {
  10. /// <summary>
  11. /// 利用WebRequest/WebResponse进行WebService调用的类
  12. /// </summary>
  13. public class WebServiceCaller
  14. {
  15. #region Tip:使用说明
  16. //webServices 应该支持Get和Post调用,在web.config应该增加以下代码
  17. //<webServices>
  18. // <protocols>
  19. // <add name="HttpGet"/>
  20. // <add name="HttpPost"/>
  21. // </protocols>
  22. //</webServices>
  23.  
  24. //调用示例:
  25. //Hashtable ht = new Hashtable(); //Hashtable 为webservice所需要的参数集
  26. //ht.Add("str", "test");
  27. //ht.Add("b", "true");
  28. //XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);
  29. //MessageBox.Show(xx.OuterXml);
  30. #endregion
  31.  
  32. /// <summary>
  33. /// 需要WebService支持Post调用
  34. /// </summary>
  35. public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
  36. {
  37. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
  38. request.Method = "POST";
  39. request.ContentType = "application/x-www-form-urlencoded";
  40. SetWebRequest(request);
  41. byte[] data = EncodePars(Pars);
  42. WriteRequestData(request, data);
  43. return ReadXmlResponse(request.GetResponse());
  44. }
  45.  
  46. /// <summary>
  47. /// 需要WebService支持Get调用
  48. /// </summary>
  49. public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
  50. {
  51. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
  52. request.Method = "GET";
  53. request.ContentType = "application/x-www-form-urlencoded";
  54. SetWebRequest(request);
  55. return ReadXmlResponse(request.GetResponse());
  56. }
  57.  
  58. /// <summary>
  59. /// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
  60. /// </summary>
  61. public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
  62. {
  63. if (_xmlNamespaces.ContainsKey(URL))
  64. {
  65. return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
  66. }
  67. else
  68. {
  69. return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
  70. }
  71. }
  72.  
  73. private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
  74. {
  75. _xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
  76. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
  77. request.Method = "POST";
  78. request.ContentType = "text/xml; charset=utf-8";
  79. request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
  80. SetWebRequest(request);
  81. byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
  82. WriteRequestData(request, data);
  83. XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
  84. doc = ReadXmlResponse(request.GetResponse());
  85.  
  86. XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
  87. mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
  88. String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
  89. doc2.LoadXml("<root>" + RetXml + "</root>");
  90. AddDelaration(doc2);
  91. return doc2;
  92. }
  93. private static string GetNamespace(String URL)
  94. {
  95. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
  96. SetWebRequest(request);
  97. WebResponse response = request.GetResponse();
  98. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  99. XmlDocument doc = new XmlDocument();
  100. doc.LoadXml(sr.ReadToEnd());
  101. sr.Close();
  102. return doc.SelectSingleNode("//@targetNamespace").Value;
  103. }
  104.  
  105. private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
  106. {
  107. XmlDocument doc = new XmlDocument();
  108. 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>");
  109. AddDelaration(doc);
  110. //XmlElement soapBody = doc.createElement_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
  111. XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
  112. //XmlElement soapMethod = doc.createElement_x_x(MethodName);
  113. XmlElement soapMethod = doc.CreateElement(MethodName);
  114. soapMethod.SetAttribute("xmlns", XmlNs);
  115. foreach (string k in Pars.Keys)
  116. {
  117. //XmlElement soapPar = doc.createElement_x_x(k);
  118. XmlElement soapPar = doc.CreateElement(k);
  119. soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
  120. soapMethod.AppendChild(soapPar);
  121. }
  122. soapBody.AppendChild(soapMethod);
  123. doc.DocumentElement.AppendChild(soapBody);
  124. return Encoding.UTF8.GetBytes(doc.OuterXml);
  125. }
  126. private static string ObjectToSoapXml(object o)
  127. {
  128. XmlSerializer mySerializer = new XmlSerializer(o.GetType());
  129. MemoryStream ms = new MemoryStream();
  130. mySerializer.Serialize(ms, o);
  131. XmlDocument doc = new XmlDocument();
  132. doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
  133. if (doc.DocumentElement != null)
  134. {
  135. return doc.DocumentElement.InnerXml;
  136. }
  137. else
  138. {
  139. return o.ToString();
  140. }
  141. }
  142.  
  143. /// <summary>
  144. /// 设置凭证与超时时间
  145. /// </summary>
  146. /// <param name="request"></param>
  147. private static void SetWebRequest(HttpWebRequest request)
  148. {
  149. request.Credentials = CredentialCache.DefaultCredentials;
  150. request.Timeout = ;
  151. }
  152.  
  153. private static void WriteRequestData(HttpWebRequest request, byte[] data)
  154. {
  155. request.ContentLength = data.Length;
  156. Stream writer = request.GetRequestStream();
  157. writer.Write(data, , data.Length);
  158. writer.Close();
  159. }
  160.  
  161. private static byte[] EncodePars(Hashtable Pars)
  162. {
  163. return Encoding.UTF8.GetBytes(ParsToString(Pars));
  164. }
  165.  
  166. private static String ParsToString(Hashtable Pars)
  167. {
  168. StringBuilder sb = new StringBuilder();
  169. foreach (string k in Pars.Keys)
  170. {
  171. if (sb.Length > )
  172. {
  173. sb.Append("&");
  174. }
  175. //sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
  176. }
  177. return sb.ToString();
  178. }
  179.  
  180. private static XmlDocument ReadXmlResponse(WebResponse response)
  181. {
  182. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  183. String retXml = sr.ReadToEnd();
  184. sr.Close();
  185. XmlDocument doc = new XmlDocument();
  186. doc.LoadXml(retXml);
  187. return doc;
  188. }
  189.  
  190. private static void AddDelaration(XmlDocument doc)
  191. {
  192. XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
  193. doc.InsertBefore(decl, doc.DocumentElement);
  194. }
  195.  
  196. private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
  197. }
  198. }

转载:

吴佳鑫的个人专栏

.net 调用webservice 总结

.net 调用webservice 总结的更多相关文章

  1. 一个简单的webservice的demo(下)winform异步调用webservice

    绕了一大圈,又开始接触winform的项目来了,虽然很小吧.写一个winform的异步调用webservice的demo,还是简单的. 一个简单的Webservice的demo,简单模拟服务 一个简单 ...

  2. 调用webservice进行身份验证

    因为同事说在调用webservice的时候会弹出身份验证的窗口,直接调用会返回401,原因是站点部署的时候设置了身份验证(账号名称自己配置).因而在调用的时候需要加入身份验证的凭证. 至于如何获取身份 ...

  3. java接口调用——webservice就是一个RPC而已

    很多新手一听到接口就蒙逼,不知道接口是什么!其实接口就是RPC,通过远程访问别的程序提供的方法,然后获得该方法执行的接口,而不需要在本地执行该方法.就是本地方法调用的升级版而已,我明天会上一篇如何通过 ...

  4. Android调用WebService

    这两天给老师做地铁app的demo,与后台的交互要用WebService,还挺麻烦的.所以想写点,希望有用. Web Services(Web服务)是一个用于支持网络间不同机器互操作的软件系统,它是一 ...

  5. C# 调用webservice 几种办法(转载)

    原文地址: http://www.cnblogs.com/eagle1986/archive/2012/09/03/2669699.html //=========================== ...

  6. 【Java EE 学习 80 下】【调用WebService服务的四种方式】【WebService中的注解】

    不考虑第三方框架,如果只使用JDK提供的API,那么可以使用三种方式调用WebService服务:另外还可以使用Ajax调用WebService服务. 预备工作:开启WebService服务,使用jd ...

  7. C#winForm调用WebService的远程接口

    Web Service 的创建简单编码.发布和部署 上一篇详细概述了WebService的创建,编码,发布和部署,那么作为客户端的程序如何访问远程端的WebService 接下来看一下具体步骤:   ...

  8. 【学习篇:他山之石,把玉攻】jquery实现调用webservice

    1.webservice端 using System; using System.Collections.Generic; using System.Web; using System.Web.Ser ...

  9. C#调用WebService

    1.1.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求, ...

  10. Atitit 动态调用webservice与客户端代理方式调用

    Atitit 动态调用webservice与客户端代理方式调用 方式1: 使用call.invoke  直接调用WSDL,缺点:麻烦,不推荐--特别是JAVA调用.NET的WS时,会有不少的问题需要解 ...

随机推荐

  1. MyEclipse7.0破解下载

    MyEclipse7.0 下载地址:downloads.myeclipseide.com/downloads/products/eworkbench/7.0M1/MyEclipse_7.0M1_E3. ...

  2. 推荐几个可以与PhoneGap很好搭配的UI框架

    - xui.js:可以被视作是jquery在phonegap上的替代品,挺好用的- jq.mobi:同上,不过体积比xui.js要大,一般还是用xui.js- jq.ui:jq.mobi配套的UI框架 ...

  3. 何查看Tomcat版本信息

    转自:http://dengjianqiang200.blog.163.com/blog/static/65811920094644354148/ 一般来说,在tomcat启动时就会有版本信息,如: ...

  4. mysql常用备注

    一:One Table  have only one Auto_Increment that column is must to be Primary key. (自增加的字段必须是主键且是数字类型) ...

  5. 对Kernel panic-not syncing:No init found...init=option to kernel错误总结!

    转载:http://blog.csdn.net/wavemcu/article/details/6950053 在移植Linux中很容易出现这样那样的问题,我也遇到过,现在就共享下人家的一些经验和自己 ...

  6. Maven-编译打包

    1. 打包时忽略测试阶段 mvn clean mvn package -DskipTests

  7. IOS 应用中从竖屏模式强制转换为横屏模式

    在 iPhone 应用里,有时我们想强行把显示模式从纵屏改为横屏(反之亦然),CocoaChina 会员 “alienblue” 为我们提供了两种思路 第一种:通过人为的办法改变view.transf ...

  8. MySQL(21):事务管理之 事务提交

    1. 现实生活中,许多操作都是需要用户确认的,例如用户删除一个文档,删除时候会弹出一个提示对话框,包含"确认"和"取消".同样的道理,在数据库中有些命令在使用的 ...

  9. Android 高级UI设计笔记15:HorizontalScrollView之 实现画廊式图片浏览器

    1. HorizontalScrollView 本来,画廊式的图片浏览器,使用Android中的Gallery就能轻松完成,但是Google说Gallery每次切换图片时都要新建视图,造成太多的资源浪 ...

  10. ProcMon启用调试符

    1.设置 _NT_SYMBOL_PATH 如果在 _NT_SYMBOL_PATH 环境变量中提供了正确的?symsrv?语法,则常见的 Mircoroft 调试工具将使用 SymSrv 技术.这些工具 ...