【.Net】调用Web API的几种方式

引言

     记录一下调用Web API的几种方式,以调用百度API为例.

HttpWebRequest

     HttpWebRequest位于System.Net命名空间,是常用的调用Web API类库.

            string strURL = "http://apis.baidu.com/apistore/weatherservice/citylist?cityname=" + HttpUtility.UrlEncode("北京");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "GET";
            request.Headers.Add("apikey", "XXXXXXXXXXXXXXXXXXXXXXXXXX");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream s = response.GetResponseStream();
            StreamReader Reader = new StreamReader(s);
            string result = Reader.ReadToEnd();

 参考链接
     HttpWebRequest 类

    在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求

    httpwebrequest详解

HttpClient 

     HttpClient 是位于System.Net.Http.HttpClient命名空间下,里面的调用都是异步的,用法也很简单.

            string strURL = "http://apis.baidu.com/apistore/weatherservice/citylist?cityname=" + HttpUtility.UrlEncode("北京");
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("apikey", "xxxxxxxxxxxxxxx");
            HttpResponseMessage response = await client.PostAsync(strURL, null);
            string reslut = await response.Content.ReadAsStringAsync();

参考链接

    C#中HttpClient使用注意:预热与长连接

    .Net 4.5中的HttpClient试用

RestSharp

    RestSharp是GitHub上的一个开源类库,用法简单方便,值得推荐. 

            RestClient restClient = new RestClient("http://apis.baidu.com/apistore/weatherservice/citylist");
            RestRequest restRequest = new RestRequest(Method.GET);
            restRequest.AddQueryParameter("cityname", "北京");
            restRequest.AddHeader("apikey", "xxxxxxxxxxxxxxx");
            string reslut = restClient.Execute(restRequest).Content;

参考链接

   RestSharp  

小结

     上文简单介绍了3个方式的用法,后面两种深度封装,使用起来很方便.性能上,我简单测试了一下,循环调用100次,耗费都是7秒多.

    

  

posted @ 2015-09-04 16:04  Caizl  阅读(1653)  评论(0编辑  收藏  举报