示例是调用谷歌短网址的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. - Visible Trees HDU - 2841 容斥原理

    题意: 给你一个n*m的矩形,在1到m行,和1到n列上都有一棵树,问你站在(0,0)位置能看到多少棵树 题解: 用(x,y)表示某棵树的位置,那么只要x与y互质,那么这棵树就能被看到.不互质的话说明前 ...

  2. 一文带你认识Docker

    Docker是一个容器技术的应用,而底层是由于Linux容器实现的,Docker只是实现层. 一.Linux容器 1.隔离与共享 一台服务器运行着多个逻辑隔离的服务器进程,谁的运行环境都不希望影响到谁 ...

  3. PowerShell随笔9--- call

    很多时候我们需要在一个脚本文件执行另外一个脚本文件,比如我们有一个Test.ps1文件 我们有以下2种方法: Invoke-Expression (&) 我们可以看到,Test.ps1中的代码 ...

  4. Jpress小程序

    首页轮播.首页公告.首页宫格.个人中心页面均支持在PC后台设置内容 首页列表.分类列表页.搜索列表的文章展示页均支持后台设置,拥有三种风格 所有分类展示支持两种风格 用户中心授权登陆,查看个人数据 J ...

  5. Zabbix 监控项更多用法

    监控服务端口状态 配置 Zabbix 提供的检测器 配置自定义值映射 查看监控项数据状态 触发器配置 自定义监控项 TCP 11 种状态 TCP 11 种状态 LISTEN - 侦听来自远方TCP端口 ...

  6. mimikatz+procdump 提取 Windows 明文密码

    0x00 原理 获取到内存文件 lsass.exe 进程 (它用于本地安全和登陆策略) 中存储的明文登录密码. 0x01 操作 Windows10/2012 以下的版本:1.上传 procdump 执 ...

  7. HCTF Warmup (phpmyadmin4.8.1的文件包含漏洞 )

    Warmup 先看hint   image.png 看url有file参数,感觉可能要用伪协议啥的,试了下,没出东西扫一下目录,发现http://warmup.2018.hctf.io/source. ...

  8. docker07-数据存储

    Docker 内部以及容器之间管理数据,在容器中管理数据主要有两种方式: 数据卷(Volumes) 挂载主机目录 (Bind mounts) 数据卷 是一个可供一个或多个容器使用的特殊目录,它绕过 U ...

  9. Web API 设计

    Web API 设计 The Design of Web APIs free online ebook https://www.manning.com/books/the-design-of-web- ...

  10. Swift All in One

    Swift All in One Swift 5.3 https://github.com/apple/swift-evolution Xcode https://developer.apple.co ...