• 【.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秒多.

        

      

  • 相关阅读:
    inotify事件监控
    NFS网络文件共享服务
    Rsync数据同步服务
    SSH连接原理及ssh-key讲解
    C语言I博客作业04
    C语言l博客作业03
    C语言I博客作业02
    定义一个计算字符串高度的方法
    字典转模型
    UIScrollView和UIPageControl
  • 原文地址:https://www.cnblogs.com/caizl/p/4781074.html
Copyright © 2020-2023  润新知