zoukankan      html  css  js  c++  java
  • Web API的几种调用方式

    示例是调用谷歌短网址的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);
                }
            }
    View Code

    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);
            }
    View Code

    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);
            }
    View Code

    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);
            }
    View Code
  • 相关阅读:
    php Thinkphp 经纬度查位置(误差200米左右)
    php redis 基础操作 Thinkphp 直接套用
    超实用的华为云服务器选购技巧经验!
    连续四年第一!华为云FusionAccess夺桌面云市场桂冠
    华为云服务器、云数据库、云安全免费送!
    Linux_CentOS_6.5安装Nginx
    PHP破解wifi密码(wifi万能钥匙的接口)
    PHP+json开发API接口实例
    52首歌,一个你
    js 获取前天、昨天、今天、明天、后天的时间
  • 原文地址:https://www.cnblogs.com/ucos/p/5682221.html
Copyright © 2011-2022 走看看