示例是调用谷歌短网址的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 的调用方式的更多相关文章

  1. OAuth在WebApi中的使用,前后台分离的调用方式

    前段时间由于公司架构服务层向WebApi转换,就研究了OAuth在WebApi中的使用,这中间遇到了很多坑,在此记录一下OAuth的正确使用方式. 1.  OAuth是做什么的? 在网上浏览时,大家都 ...

  2. WebApi的调用-2.后台调用

    httpClient调用方式 namespace SOA.Common { //httpClient调用WebApi public class HttpClientHelper { public st ...

  3. 【转】java通用URL接口地址调用方式GET和POST方式

    java通用URL接口地址调用方式GET和POST方式,包括建立请求和设置请求头部信息等等......... import java.io.ByteArrayOutputStream; import ...

  4. java 实现WebService 以及不同的调用方式

    webservice:    就是应用程序之间跨语言的调用    wwww.webxml.com.cn    1.xml    2.    wsdl: webservice description l ...

  5. Wcf:可配置的服务调用方式

    添加wcf服务引用时,vs.net本来就会帮我们在app.config/web.config里生成各种配置,这没啥好研究的,但本文谈到的配置并不是这个.先看下面的图: 通常,如果采用.NET的WCF技 ...

  6. Winform开发框架的业务对象统一调用方式

    在这个纷繁的社会里面,统一性的特点能够带来很多高效的产出.牢固的记忆,这种特征无论对于企业.个人的开发工作,知识的传承都有着非常重要的作用,Winfrom框架本身就是基于这个理念而生,从统一的数据库设 ...

  7. WM_QUIT,WM_CLOSE,WM_DESTROY 消息出现顺序及调用方式

    http://bbs.ednchina.com/BLOG_ARTICLE_3005455.HTM VC中WM_CLOSE.WM_DESTROY.WM_QUIT消息出现顺序及调用方式 wxleasyla ...

  8. Webservice 调用方式整理

    前一段时间搞webservice,简单的记录了一下几种常用的调用方式,供大家参考. 第一种:Java proxy 1).用过eclipse的创建web service client来完成 2).在ec ...

  9. magento 列表页显示产品属性值的几种调用方式

    之前有人提到要在列表显示一些特定的属性,除了自带的名字,价格等.因为列表页和产品页都有一个同名的产品对象:$_product,而在产品页,$_product是直接可以用$_product->ge ...

随机推荐

  1. Codeforces Round #521 (Div. 3) E. Thematic Contests (离散化,二分)

    题意:有\(n\)个话题,每次都必须选取不同的话题,且话题数必须是上次的两倍,第一次的话题数可以任意,问最多能选取多少话题数. 题解:我们首先用桶来记录不同话题的数量,因为只要求话题的数量,与话题是多 ...

  2. Docker架构分解

    Docker总架构分解Docker对使用者来讲是一个C/S模式的架构,而Docker的后端是一个非常松耦合的架构,模块各司其职,并有机组合,支撑Docker的运行. 用户是使用Docker Clien ...

  3. codeforce 3C

    B. Lorry time limit per test 2 seconds memory limit per test 64 megabytes input standard input outpu ...

  4. js Promise finally All In One

    js Promise finally All In One finally let isLoading = true; fetch(myRequest).then(function(response) ...

  5. javascript module system all in one

    javascript module system all in one AMD & CMD https://github.com/amdjs/amdjs-api/wiki/AMD http:/ ...

  6. JavaScript Functional Programming

    JavaScript Functional Programming JavaScript 函数式编程 anonymous function https://en.wikipedia.org/wiki/ ...

  7. Flutter & Scaffold & multiple floatingActionButton

    Flutter & Scaffold & multiple floatingActionButton demo import 'package:flutter/material.dar ...

  8. OLAP

    OLAP Online Analytical Processing https://en.wikipedia.org/wiki/Online_analytical_processing 在线分析处理 ...

  9. npm install 原理

    npm install 原理 https://docs.npmjs.com/about-npm/ npm consists of three distinct components: the webs ...

  10. taro H5

    taro H5 开发指南 https://nervjs.github.io/taro/docs/GETTING-STARTED.html#h5 taro # build $ taro build -- ...