WEBAPI 的调用方式
示例是调用谷歌短网址的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 的调用方式的更多相关文章
- OAuth在WebApi中的使用,前后台分离的调用方式
前段时间由于公司架构服务层向WebApi转换,就研究了OAuth在WebApi中的使用,这中间遇到了很多坑,在此记录一下OAuth的正确使用方式. 1. OAuth是做什么的? 在网上浏览时,大家都 ...
- WebApi的调用-2.后台调用
httpClient调用方式 namespace SOA.Common { //httpClient调用WebApi public class HttpClientHelper { public st ...
- 【转】java通用URL接口地址调用方式GET和POST方式
java通用URL接口地址调用方式GET和POST方式,包括建立请求和设置请求头部信息等等......... import java.io.ByteArrayOutputStream; import ...
- java 实现WebService 以及不同的调用方式
webservice: 就是应用程序之间跨语言的调用 wwww.webxml.com.cn 1.xml 2. wsdl: webservice description l ...
- Wcf:可配置的服务调用方式
添加wcf服务引用时,vs.net本来就会帮我们在app.config/web.config里生成各种配置,这没啥好研究的,但本文谈到的配置并不是这个.先看下面的图: 通常,如果采用.NET的WCF技 ...
- Winform开发框架的业务对象统一调用方式
在这个纷繁的社会里面,统一性的特点能够带来很多高效的产出.牢固的记忆,这种特征无论对于企业.个人的开发工作,知识的传承都有着非常重要的作用,Winfrom框架本身就是基于这个理念而生,从统一的数据库设 ...
- WM_QUIT,WM_CLOSE,WM_DESTROY 消息出现顺序及调用方式
http://bbs.ednchina.com/BLOG_ARTICLE_3005455.HTM VC中WM_CLOSE.WM_DESTROY.WM_QUIT消息出现顺序及调用方式 wxleasyla ...
- Webservice 调用方式整理
前一段时间搞webservice,简单的记录了一下几种常用的调用方式,供大家参考. 第一种:Java proxy 1).用过eclipse的创建web service client来完成 2).在ec ...
- magento 列表页显示产品属性值的几种调用方式
之前有人提到要在列表显示一些特定的属性,除了自带的名字,价格等.因为列表页和产品页都有一个同名的产品对象:$_product,而在产品页,$_product是直接可以用$_product->ge ...
随机推荐
- Codeforces Round #578 (Div. 2) C. Round Corridor (思维,数论)
题意: 有一个分两层的圆盘,每层从12点方向均分插入\(n\)和\(m\)个隔板,当内层和外层的隔板相连时是不能通过的,有\(q\)个询问,每次给你内层或外层的两个点,判断是否能从一个点走到另外一个点 ...
- Leetcode(38)-报数
报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数.其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被读作 "one 1&quo ...
- MacOS微信逆向分析-Frida
MacOS微信逆向分析-Frida 0.前言 PC下的微信二次开发相信大家都会了,那么本篇文章将带领大家使用Frida框架对Mac下微信来进行二次开发! PS:还有一种静态注入的方式也不错,但是考虑到 ...
- TestNG学习-依赖
背景: 有时,需要按特定顺序调用测试方法.例如: 在运行更多测试方法之前,请确保一定数量的测试方法已经完成并成功. 在希望将初始化的方法也用作测试方法的同时初始化测试项目. TestNG允许使用注解或 ...
- vuepress & package.json lock version
vuepress & package.json lock version npm 锁版 bug npm lock version holy shit { "name": & ...
- Python Learning Paths
Python Learning Paths Python Expert Python in Action Syntax Python objects Scalar types Operators St ...
- live chat for website UX
live chat for website UX increase customer satisfaction using a live chat https://crisp.chat/en/live ...
- API protocols All In One
API protocols All In One SOAP vs. REST vs. JSON-RPC vs. gRPC vs. GraphQL vs. Thrift https://www.mert ...
- Flutter: ValueListenableBuilder 内容与ValueListenable保持"同步"的窗口小部件
API 使用这个修改状态可以不用setState(). class _MyHomeState extends State<MyHome> { final ValueNotifier< ...
- 嵌入式开发板使用网口和nfs进行文件共享
如果你的开发板有网口,类似于这玩意. 那么,你可以去买根网线,类似于这玩意. 然后你就可以将你的电脑和开发板用网线连起来,通过nfs(网络文件系统)来进行文件夹共享,文件夹共享就相当于挂载,nfs是利 ...