C# 调用WebService的方式汇总
一、调用方式
方式一:根据提供的webservice地址,用VS自带工具生成cs文件,添加到项目中使用即可。
工具:
步骤一:如果本地访问不了webservice地址,则通过远端生成wsdl文件,拷贝到本地用工具生成cs类文件,导入项目中。
1.获取webservice地址;
2.在浏览器中访问webservice地址,此处访问需要在地址后面加上 ?wsdl
例如:原地址:http://42.123.92.137:1010/interface/Hospital_Interface.asmx
访问时:http://42.123.92.137:1010/interface/Hospital_Interface.asmx?wsdl
3.将网页中的数据另存为 (xxx.wsdl)文件,
3.用VS自带工具将上一步生成的(xxx.wsdl)文件通过命令生成 (xxx.cs) 类文件。
(1)直接通过wsdl文件位置生成。公式:wsdl + wsdl文件路径 + /out:+ cs生成文件路径
例:wsdl E:\service.wsdl /out:E:/WebServicetest.cs
(2)生成带有命名空间的cs文件。公式:wsdl + wsdl文件路径 + /n:命名空间名称 +/out:+ cs生成文件路径
例:wsdl E:\service.wsdl /n:test /out:E:/WebServicetest.cs
步骤二:如果本地可以直接访问到webservice地址,直接通过VS工具生成
生成公式:wsdl /n:+命名空间名称+ /out:+cs类文件路径+文件名称.cs+ webservice地址+?wsdl (注意公式里面空格的地方)
例:wsdl /n:xx /out:D:/web.cs http://192.168.0.222/WebSite/Service.asmx?wsdl
方式二:根据webservice地址,动态在项目中生成代理类文件,通过反射调用即可
1.将webservice地址存放到配置文件中,代码中通过读取地址生成代理类。
1 /// <summary> 2 /// 根据webservice地址生成代理类 3 /// </summary> 4 /// <param name="url">本地配置文件中webservice地址</param> 5 /// <returns></returns> 6 public static int InitCreatClass(string url) 7 { 8 try 9 { 10 11 //使用 XmlTextReader 对象创建和格式化 WSDL 文档 12 XmlTextReader reader = new XmlTextReader(url + "?wsdl"); 13 ServiceDescription serviceDes = ServiceDescription.Read(reader); 14 15 16 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); 17 sdi.AddServiceDescription(serviceDes, "", ""); 18 CodeNamespace cnspace = new CodeNamespace(@namespace); 19 20 //生成客户端代理类 21 CodeCompileUnit ccUnit = new CodeCompileUnit(); 22 ccUnit.Namespaces.Add(cnspace); 23 sdi.Import(cnspace, ccUnit); 24 CSharpCodeProvider cscProvider = new CSharpCodeProvider(); 25 ICodeCompiler icc = cscProvider.CreateCompiler(); 26 27 //设置编译参数 28 CompilerParameters copParameters = new CompilerParameters(); 29 copParameters.GenerateExecutable = false; 30 copParameters.GenerateInMemory = true; 31 copParameters.OutputAssembly = "TestWebService.dll"; 32 copParameters.ReferencedAssemblies.Add("System.dll"); 33 copParameters.ReferencedAssemblies.Add("System.XML.dll"); 34 copParameters.ReferencedAssemblies.Add("System.Web.Services.dll"); 35 copParameters.ReferencedAssemblies.Add("System.Data.dll"); 36 37 //编译代理类 38 CompilerResults comResults = icc.CompileAssemblyFromDom(copParameters, ccUnit); 39 if (true == comResults.Errors.HasErrors) 40 { 41 42 System.Text.StringBuilder sb = new System.Text.StringBuilder(); 43 foreach (System.CodeDom.Compiler.CompilerError ce in comResults.Errors) 44 { 45 sb.Append(ce.ToString()); 46 sb.Append(System.Environment.NewLine); 47 } 48 throw new Exception(sb.ToString()); 49 } 50 } 51 catch (Exception ex) 52 { 53 throw new Exception(ex.Message); 54 } 55 return 0; 56 }
2.访问代理类,调用类中的函数
1 /// <summary> 2 /// 调用代理类函数 3 /// </summary> 4 /// <param name="methodname">函数名称</param> 5 /// <param name="args">入参</param> 6 /// <returns></returns> 7 public static object InvokeWebService(string methodname, object[] args) 8 { 9 try 10 { 11 //通过反射调用代理类函数 12 System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom("TestWebService.dll"); 13 Type t = asm.GetType(classname); 14 15 object o = Activator.CreateInstance(t); 16 System.Reflection.MethodInfo method = t.GetMethod(methodname); 17 return method.Invoke(o, args); 18 } 19 catch (Exception ex) 20 { 21 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); 22 } 23 } 24 25 /// <summary> 26 /// 函数调用 27 /// </summary> 28 private void TestInvoke() 29 { 30 string[] ReqParms = new string[4];//参数数量 31 ReqParms[0] = "参数1"; 32 ReqParms[1] = "参数2"; 33 ReqParms[2] = "参数3"; 34 ReqParms[3] = "参数4"; 35 36 //Func_Name 被调用函数名称 37 string result = InvokeWebServiceD("Func_Name", ReqParms).ToString(); 38 }
方式三:通过 HttpWebRequest 直接调用webservice中的函数
构建httprequest帮助类
1 public partial class HttpHelper 2 { 3 private static HttpHelper m_Helper; 4 5 /// <summary> 6 /// 单例模式 7 /// </summary> 8 public static HttpHelper Helper 9 { 10 get { return m_Helper ?? (m_Helper = new HttpHelper()); } 11 } 12 13 /// <summary> 14 /// 获取请求的数据 15 /// </summary> 16 /// <param name="strUrl">请求地址</param> 17 /// <param name="requestMode">请求方式</param> 18 /// <param name="parameters">参数</param> 19 /// <param name="requestCoding">请求编码</param> 20 /// <param name="responseCoding">响应编码</param> 21 /// <param name="timeout">请求超时时间(毫秒)</param> 22 /// <returns>请求成功响应信息,失败返回null</returns> 23 public string GetResponseString(string strUrl, ERequestMode requestMode, Dictionary<string, string> parameters, Encoding requestCoding, Encoding responseCoding, int timeout = 300) 24 { 25 string url = VerifyUrl(strUrl); 26 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url)); 27 28 HttpWebResponse webResponse = null; 29 switch (requestMode) 30 { 31 case ERequestMode.Get: 32 webResponse = GetRequest(webRequest, timeout); 33 break; 34 case ERequestMode.Post: 35 webResponse = PostRequest(webRequest, parameters, timeout, requestCoding); 36 break; 37 } 38 39 if (webResponse != null && webResponse.StatusCode == HttpStatusCode.OK) 40 { 41 using (Stream newStream = webResponse.GetResponseStream()) 42 { 43 if (newStream != null) 44 using (StreamReader reader = new StreamReader(newStream, responseCoding)) 45 { 46 string result = reader.ReadToEnd(); 47 return result; 48 } 49 } 50 } 51 return null; 52 } 53 54 55 /// <summary> 56 /// get 请求指定地址返回响应数据 57 /// </summary> 58 /// <param name="webRequest">请求</param> 59 /// <param name="timeout">请求超时时间(毫秒)</param> 60 /// <returns>返回:响应信息</returns> 61 private HttpWebResponse GetRequest(HttpWebRequest webRequest, int timeout) 62 { 63 try 64 { 65 webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; 66 webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5"); 67 webRequest.Headers.Add("Cache-Control", "no-cache"); 68 webRequest.UserAgent = "DefaultUserAgent"; 69 webRequest.Timeout = timeout; 70 webRequest.Method = "GET"; 71 72 // 接收返回信息 73 HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); 74 return webResponse; 75 } 76 catch (Exception ex) 77 { 78 return null; 79 } 80 } 81 82 83 /// <summary> 84 /// post 请求指定地址返回响应数据 85 /// </summary> 86 /// <param name="webRequest">请求</param> 87 /// <param name="parameters">传入参数</param> 88 /// <param name="timeout">请求超时时间(毫秒)</param> 89 /// <param name="requestCoding">请求编码</param> 90 /// <returns>返回:响应信息</returns> 91 private HttpWebResponse PostRequest(HttpWebRequest webRequest, Dictionary<string, string> parameters, int timeout, Encoding requestCoding) 92 { 93 try 94 { 95 // 拼接参数 96 string postStr = string.Empty; 97 if (parameters != null) 98 { 99 parameters.All(o => 100 { 101 if (string.IsNullOrEmpty(postStr)) 102 postStr = string.Format("{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value)); 103 else 104 postStr += string.Format("&{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value)); 105 106 return true; 107 }); 108 } 109 110 byte[] byteArray = requestCoding.GetBytes(postStr); 111 webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01"; 112 webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5"); 113 webRequest.Headers.Add("Cache-Control", "no-cache"); 114 webRequest.UserAgent = "DefaultUserAgent"; 115 //webRequest.Timeout = timeout; 116 webRequest.ContentType = "application/x-www-form-urlencoded"; 117 webRequest.ContentLength = byteArray.Length; 118 webRequest.Method = "POST"; 119 120 // 将参数写入流 121 using (Stream newStream = webRequest.GetRequestStream()) 122 { 123 newStream.Write(byteArray, 0, byteArray.Length); 124 newStream.Close(); 125 } 126 127 // 接收返回信息 128 HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); 129 return webResponse; 130 } 131 catch (Exception ex) 132 { 133 return null; 134 } 135 } 136 137 138 /// <summary> 139 /// 验证URL 140 /// </summary> 141 /// <param name="url">待验证 URL</param> 142 /// <returns></returns> 143 private string VerifyUrl(string url) 144 { 145 if (string.IsNullOrEmpty(url)) 146 throw new Exception("URL 地址不可以为空!"); 147 148 if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase)) 149 return url; 150 151 return string.Format("http://{0}", url); 152 } 153 154 } 155 156 public enum ERequestMode 157 { 158 Get, 159 Post 160 }
调用方式
1 /// <summary> 2 /// 测试调用 3 /// </summary> 4 private void TestInvoke() 5 { 6 //组织参数 7 Dictionary<string, string> parameters = new Dictionary<string, string>(); 8 parameters.Add("CantonCode", PersonInfo.RegionNumber); 9 parameters.Add("CardCode", PersonInfo.CardNo); 10 parameters.Add("Name", txtName.Text); 11 parameters.Add("CompHosCode", SystemConfigData.HospitalCode); 12 13 string _result = HttpHelper.Helper.GetResponseString(url, ERequestMode.Post, parameters, Encoding.Default, Encoding.UTF8); 14 }
以下是对上面三种方式进行总结。
方式一、
优点:利用地址直接生成cs类,操作方便快捷,发生错误机率小,调用简单;
缺点:如果webservice地址或者内容发生改变,项目必须重新生成cs文件,导致项目维护性差;
采用场景:webservice接口已经趋于稳定,不会有变动的情况下可使用这种方式;
方式二、
优点:将webservice地址放在配置文件中,一旦地址放生变化,只需要修改配置文件即可,项目维护性好;
缺点:对webservice接口要求比较高,不规范的webservice接口,生成代理类时会发生错误;
采用场景:webservice接口规范,且变动小时,可采用此种方式;
方式三、
优点:添加帮助类,然后调用即可,方便快捷,webservice地址放置在配置文件中,易于维护;
缺点:暂时未发现较大缺点;
采用场景:任何webservice接口,均可采用此种方式;
使用推荐:方式三 > 方式一 > 方式二