WebService几种调用方法
Posted 一发寒冰箭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebService几种调用方法相关的知识,希望对你有一定的参考价值。
首先添加WebService服务端方法
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebApplication2 { /// <summary> /// WebService1 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod (EnableSession = true)]//标记为服务方法 public string CountSum(string param1, string param2) { decimal num1 = Convert.ToInt32(param1); decimal num2 = Convert.ToInt32(param2); decimal sum = num1 + num2; return sum.ToString(); } } }
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.Text; using System.Web.Services.Description; using System.Xml.Serialization; using System.Windows.Forms; using System.Xml; namespace WebServiceForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //cn.com.webxml.www.WeatherWebService weatherWebService = new cn.com.webxml.www.WeatherWebService(); //string[] vsArr = weatherWebService.getWeatherbyCityName(this.textBox1.Text); //localhost.WebService1 webService1 = new localhost.WebService1(); //this.textBox2.Text = webService1.HelloWorld(); //this.textBox1.Text = Convert.ToString(webService1.HelloWorld()); //ServiceReference1.CalculateServiceClient calculateServiceClient = new ServiceReference1.CalculateServiceClient(); //this.textBox2.Text = Convert.ToString(calculateServiceClient.AddSum(10, 10)); //localhost2.CalculateService calculateService = new localhost2.CalculateService(); //this.textBox2.Text = Convert.ToString(calculateService.AddSum(1,1)); //var client = new HttpClient(); //client.BaseAddress = new Uri("http://localhost:22650/"); //var str =await client.GetStringAsync("WebApplication4/News/GetAllNews"); //第一种采用动态代理 //反射、CodeDom WebClient webClient = new WebClient(); string url = "http://localhost:10925/WebService1.asmx?WSDL";//可以设置 Stream stream = webClient.OpenRead(url); ServiceDescription serviceDescription = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter();//创建客户端代理类 importer.ProtocolName = "Soap"; importer.Style = ServiceDescriptionImportStyle.Client;//生成客户端代理 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(serviceDescription, "", ""); CodeNamespace codeNamespace = new CodeNamespace();//命名空间 codeNamespace.Name = "TestWebservice"; CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); ServiceDescriptionImportWarnings warnings = importer.Import(codeNamespace, codeCompileUnit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.OutputAssembly = "MyTest.dll"; parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.XML.dll"); parameters.ReferencedAssemblies.Add("System.Web.Services.dll"); parameters.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults results = provider.CompileAssemblyFromDom(parameters, codeCompileUnit); if (results.Errors.HasErrors) { } Assembly assembly = Assembly.LoadFrom("MyTest.dll"); Type t = assembly.GetType("TestWebservice.WebService1"); object o = Activator.CreateInstance(t); MethodInfo methodInfo = t.GetMethod("HelloWorld"); string str = Convert.ToString(methodInfo.Invoke(o, null)); this.textBox2.Text = str; //第二种利用http 协议的get 和post,HttpWebRequest,HttpWebResponse,Stream string url2 = "http://localhost:10925/WebService1.asmx"; string result = ""; string param = ""; byte[] bytes= null; Stream requeststream = null; HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; decimal num1 = 1, num2 = 4; param = HttpUtility.UrlEncode("param1") + "=" + HttpUtility.UrlEncode(Convert.ToString(num1)) + "&" + HttpUtility.UrlEncode("param2") + "=" + HttpUtility.UrlEncode(Convert.ToString(num2)); bytes = Encoding.UTF8.GetBytes(param); httpWebRequest =(HttpWebRequest)WebRequest.Create(url2 + "/"+ "CountSum"); httpWebRequest.Method = "POST"; httpWebRequest.ContentType= "application/x-www-form-urlencoded"; httpWebRequest.ContentLength = bytes.Length; requeststream = httpWebRequest.GetRequestStream(); requeststream.Write(bytes,0, bytes.Length); requeststream.Close(); try { httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); } catch(Exception ex) { MessageBox.Show(ex.Message); } Stream ResponseStream = httpWebResponse.GetResponseStream(); XmlTextReader xmlTextReader = new XmlTextReader(ResponseStream); xmlTextReader.MoveToContent(); result = xmlTextReader.ReadInnerXml(); //StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(),Encoding.UTF8); //result = streamReader.ReadToEnd(); this.textBox1.Text = result; requeststream.Dispose(); requeststream.Close(); ResponseStream.Dispose(); ResponseStream.Close(); httpWebResponse.Dispose(); httpWebResponse.Close(); xmlTextReader.Dispose(); xmlTextReader.Close(); } } }
最后结果
与添加Web引用对比
通常我们在程序中需要调用WebService时,都是通过“添加Web引用”,让VS.NET环境来为我们生成服务代理,然后调用对应的Web服务。这样是使工作简单了,但是却和提供Web服务的URL、方法名、参数绑定在一起了,这是VS.NET自动为我们生成Web服务代理的限制。如果哪一天发布Web服务的URL改变了,则我们需要重新让VS.NET生成代理,并重新编译。在某些情况下,这可能是不能忍受的,我们需要动态调用WebService的能力。比如我们可以把Web服务的URL保存在配置文件中,这样,当服务URL改变时,只需要修改配置文件就可以了
//webServices 应该支持Get和Post调用,在webservices下的web.config应该增加以下代码 //<webServices> // <protocols> // <add name="HttpGet"/> // <add name="HttpPost"/> // </protocols> //</webServices>
以上是关于WebService几种调用方法的主要内容,如果未能解决你的问题,请参考以下文章