首页 > Windows开发 > 详细

WEBAPI 的调用方式

时间:2020-12-01 18:07:09      阅读:29      评论:0      收藏:0      [点我收藏+]

示例是调用谷歌短网址的API.

1. HttpClient方式

public static async void DoAsyncPost()
        {
            DateTime dateBegin = DateTime.Now;

            string url = @"https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAK2z18";
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                RequestModel model = new RequestModel
                {
                    longUrl = "https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx"
                };

                string data = SimpleJson.SerializeObject(model);
                HttpContent content = new StringContent(data);

                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = await http.PostAsync(url, content);

                response.EnsureSuccessStatusCode();

                var result = await response.Content.ReadAsStringAsync();

                ResponseModel responseModel = (ResponseModel)SimpleJson.DeserializeObject(result.ToString(), typeof(ResponseModel));

                http.Dispose();
                response.Dispose();

                DateTime dateEnd = DateTime.Now;
                TimeSpan span = dateEnd.Subtract(dateBegin);
                Console.WriteLine("HttpClient Time Span is:{0}", span.Milliseconds);

                Console.WriteLine(result);
            }
        }
 

2. WebClient方式

public static void WebClientPost()
        {
            DateTime dateBegin = DateTime.Now;

            Encoding encoding = Encoding.UTF8;
            string result = string.Empty;
            string uri = @"https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAK2z18";
            WebClient wc = new WebClient();

            RequestModel model = new RequestModel
            {
                longUrl = "https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx"
            };

            string paramStr = SimpleJson.SerializeObject(model);
            //string paramStr = "{\"longUrl\": \"https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx\"}";
            wc.Headers.Add("Content-Type", "application/json");
            byte[] postData = encoding.GetBytes(paramStr);


            byte[] responseData = wc.UploadData(uri, "POST", postData);
            result = encoding.GetString(responseData);

            ResponseModel responseModel = (ResponseModel)SimpleJson.DeserializeObject(result, typeof(ResponseModel));

            DateTime dateEnd = DateTime.Now;
            TimeSpan span = dateEnd.Subtract(dateBegin);
            Console.WriteLine("WebClient Time Span is:{0}", span.Milliseconds);

            Console.WriteLine(result);
        }
 

3. RestClient方式:,要用NuGet安装RestSharp


 
public static void RestClientPost()
        {
            DateTime dateBegin = DateTime.Now;

            var client = new RestClient("https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAK2z18");
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/json");

            RequestModel model = new RequestModel
            {
                longUrl = "https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx"
            };

            string paramStr = SimpleJson.SerializeObject(model);
            request.AddParameter("application/json", paramStr, ParameterType.RequestBody);
            //request.AddParameter("application/json", "{\"longUrl\": \"https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx\"}", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            ResponseModel responseModel = (ResponseModel)SimpleJson.DeserializeObject(response.Content, typeof(ResponseModel));

            DateTime dateEnd = DateTime.Now;
            TimeSpan span = dateEnd.Subtract(dateBegin);
            Console.WriteLine("RestClient Time Span is:{0}", span.Milliseconds);

            Console.WriteLine(response.Content);
        }
 

4. HttpWebRequest方式:


 
public static void HttpWebRequestPost()
        {
            DateTime dateBegin = DateTime.Now;
            string url = @"https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAK2z18";
            string contentType = "application/json";

            RequestModel model = new RequestModel
            {
                longUrl = "https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx"
            };

            string body = SimpleJson.SerializeObject(model);

            //string body = "{\"longUrl\": \"https://msdn.microsoft.com/zh-CN/library/system.net.http.httpclient(VS.110).aspx\"}";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = contentType;
            httpWebRequest.Headers.Add("cache-control", "no-cache");
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            byte[] btBodys = Encoding.UTF8.GetBytes(body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
            string responseContent = streamReader.ReadToEnd();

            httpWebResponse.Close();
            streamReader.Close();
            httpWebRequest.Abort();
            httpWebResponse.Close();

            ResponseModel responseModel = (ResponseModel)SimpleJson.DeserializeObject(responseContent, typeof(ResponseModel));

            DateTime dateEnd = DateTime.Now;
            TimeSpan span = dateEnd.Subtract(dateBegin);
            Console.WriteLine("HttpWebResponse Time Span is:{0}", span.Milliseconds);

            Console.WriteLine(responseContent);
        }
 

 

WEBAPI 的调用方式

原文:https://www.cnblogs.com/David-Dai/p/14068678.html

(0)
(0)
   
举报
评论 一句话评论(0
分享档案
最新文章
教程昨日排行
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!