初探WebService

WebService的使用还是很简单的,主要的使用方法可以按照网上的基础教程参考,也就是添加web application那一套;

然后可以直接在项目中使用,在同解决方案中的另一个项目中“引用服务”,这一步有个要注意的;

就是引用服务前记得先编译就好了,否则会无法引用;

webservice想比与webapi有个什么好处呢?

真的是使用起来太方便了,相当于直接调用函数了;

参考如下用法:

 1 WeatherWSSoap ws = new WeatherWSSoapClient();//自定义命名空间
 2 string[] a = ws.getRegionProvince();//调用方法
 3 foreach (var item in a)
 4 {
 5    Console.WriteLine(item);
 6 }
 7 
 8 try
 9 {
10    MyCustomSoapClient mc = new MyCustomSoapClient();//本地的webservice
11    Console.WriteLine(mc.HelloWorld());//调用方法
12 }
13 catch (Exception ex)
14 {
15    Console.WriteLine(ex.Message);
16    throw;
17 }

这里我使用的webservice是http://ws.webxml.com.cn/WebServices/WeatherWS.asmx这个地址;

----------------------------------------

当然了,还可以使用httpwebrequest的方法访问,但是这样可就不太具有操作性了,不推荐!

代码如下:

1 HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.webxml.com.cn/WebServices/WeatherWS.asmx/getRegionProvince");
2 req.Method = "GET";
3 
4 HttpWebResponse res = (HttpWebResponse)req.GetResponse();
5 Stream resStream = res.GetResponseStream();
6 StreamReader strReader = new StreamReader(resStream, Encoding.UTF8);
7 string data = strReader.ReadToEnd();
8 Console.WriteLine(data);

猜你喜欢

转载自www.cnblogs.com/LeeSki/p/12153185.html