原文地址:https://blog.csdn.net/chinacsharper/article/details/21256569php
今天碰巧,用到了淘寶的在線IP地址查詢的Rest API,它提供接口給用戶查詢IP地址的歸宿地。數據庫比較龐大,準確性也比較高。地址爲:http://ip.taobao.com/instructions.php。html

這是一個GET請求的接口,使用方式很簡單,只要將這個URL複製到瀏覽器的地址欄就能夠了。web

能夠看到接口返回的是一串JSON格式的字符串。關於如何解析JSON,參考個人這篇博文:http://blog.csdn.net/chinacsharper/article/details/9246627。數據庫
那麼如何在程序中實現呢?咱們新建一個控制檯應用程序,並鍵入以下代碼:瀏覽器
- namespace RestServiceApp
- {
- class Program
- {
- static void Main(string[] args)
- {
- string url = "http://ip.taobao.com/service/getIpInfo.php?ip=210.75.225.254";
- HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
- WebResponse response = request.GetResponse();
- StreamReader reader = new StreamReader(response.GetResponseStream());
- Console.WriteLine(reader.ReadToEnd());
- }
- }
- }
運行它能夠看到:測試

關於如何解碼\u4e2d\u56fd這樣的字符串,能夠參考個人這篇博文:http://blog.csdn.net/chinacsharper/article/details/9885165。編碼
好了,如何調用這個淘寶IP地址的接口就到這,不過我由此想到了兩個東西,一個是WCF Rest,一個是ASP.NET MVC中的Web Api,這裏先介紹一下WCF Rest。url
咱們在前文也簡單的講解過如何使用WCF,WCF最關鍵的要素就是A(Address地址)、B(Binding綁定)、C(Contract契約)。爲了便於演示,咱們直接用控制檯應用程序做爲WCF Rest的宿主程序,先創建一個類庫項目,裏面的代碼以下。spa
- namespace Service.Interface
- {
- [ServiceContract]
- public interface IAddress
- {
- [WebGet(UriTemplate = "ip={ip}")]
- Address Get(string ip);
- }
-
- [DataContract]
- public class Address
- {
- [DataMember]
- public string IPAddress { get; set; }
-
- [DataMember]
- public string Province { get; set; }
-
- [DataMember]
- public string City { get; set; }
- }
- }
很簡單,就是定義了一個契約,用於獲取IP地址信息。須要說明一下,這個項目須要引用System.ServiceModel和System.Runtime.Serialization這兩個dll。操作系統
接下來就是要建立一個WCF Rest服務端程序,用以提供服務。
先定義一個類AddressService,並實現咱們剛剛定義的IAddress接口。
- namespace Service
- {
- public class AddressService : IAddress
- {
- private static IList<Address> addresses = new List<Address>();
-
- static AddressService()
- {
-
- addresses.Add(new Address() { IPAddress = "210.75.225.254", Province = "上海市", City = "上海市" });
- }
-
- public Address Get(string ipAddress)
- {
- return addresses.FirstOrDefault(x => x.IPAddress == ipAddress);
- }
- }
- }
接着在App.config配置文件中添加配置信息。
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
- </startup>
-
- <system.serviceModel>
- <services>
- <service name="Service.AddressService">
- <endpoint address="http://127.0.0.1:8888/addresses"
- binding="webHttpBinding"
- contract="Service.Interface.IAddress"/>
- </service>
- </services>
- </system.serviceModel>
- </configuration>
最後在Main方法中添加以下代碼。
- namespace Service
- {
- class Program
- {
- static void Main(string[] args)
- {
- using (WebServiceHost host = new WebServiceHost(typeof(AddressService)))
- {
- host.Open();
- Console.Read();
- }
- }
- }
- }
而後咱們就能夠運行這個控制檯項目了。注意:運行程序時,請確保你當前的用戶爲操做系統管理員用戶。
服務端準備好,咱們寫一下客戶端的調用代碼,在控制檯應用程序中測試一下這個WCF Rest服務。
一樣的,咱們須要先在客戶端的App.config文件中配置一下這個服務(也能夠在代碼中經過硬編碼的方式進行)。
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
- </startup>
- <system.serviceModel>
- <client>
- <endpoint name="addressService"
- address="http://127.0.0.1:8888/addresses"
- binding="webHttpBinding"
- contract="Service.Interface.IAddress" />
- </client>
- </system.serviceModel>
- </configuration>
這裏要注意,綁定模型要跟服務端模型一致,不然會有綁定不匹配的異常產生。
客戶端代碼:
- namespace RestServiceApp
- {
- class Program
- {
- static void Main(string[] args)
- {
- using (ChannelFactory<IAddress> channelFactory = new ChannelFactory<IAddress>("addressService"))
- {
- IAddress iAddress = channelFactory.CreateChannel();
- Address address = iAddress.Get("210.75.225.254");
-
- if (address != null)
- {
- Console.WriteLine(string.Format("IP來自{0},{1}",address.Province,address.City));
- }
- }
- }
- }
- }
保證以前創建的服務端程序在運行狀態,而後咱們運行一下這個客戶端程序:

能夠看到,咱們調用WCF Rest服務成功的得到了IP地址的詳細信息。
既然是Get請求型的Rest服務,那麼應該能夠在瀏覽器中直接調用,咱們打開瀏覽器輸入地址。

一樣的得到了XML類型的數據。
那若是咱們想提供JSON格式的數據給別人呢?很簡單,只要在定義接口方法時,指定數據返回的格式便可。
- [ServiceContract]
- public interface IAddress
- {
- [WebGet(UriTemplate = "ip={ip}", ResponseFormat = WebMessageFormat.Json)]
- Address Get(string ip);
- }

看到這裏,你是否以爲Rest很是簡單易用呢?