示例是调用谷歌短网址的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 #428 (Div. 2) C. Journey (简单搜索)

    题意:给你一颗树(边是无向的),从根节点向下走,统计走到每个子节点的概率,求所有叶子节点的深度乘上概率的和. 题解:每层子节点的概率等于上一层节点的概率乘\(1\)除以这层的子节点数,所以我们用\(d ...

  2. HihoCoder - 1110

    题意: 您的任务是判断输入是否是合法的正则表达式.正则表达式定义如下: 1: 0和1都是正则表达式. 2:如果P和Q是正则表达式,那么PQ就是正则表达式. 3:如果P是正则表达式,(P)就是正则表达式 ...

  3. XHXJ's LIS HDU - 4352 最长递增序列&数位dp

    代码+题解: 1 //题意: 2 //输出在区间[li,ri]中有多少个数是满足这个要求的:这个数的最长递增序列长度等于k 3 //注意是最长序列,可不是子串.子序列是不用紧挨着的 4 // 5 // ...

  4. PowerShell随笔5---添加.NET类型

    有些情况下,有些脚本命令不能满足我们的需求,而手头却能用C#很方便的实现. 我们就可以把自定义的类型Add到PowerShell中使用,使用方法和PowerShell调用.NET类库方法是一样的. 以 ...

  5. linux repo init 遇到的问题

    问题描述: 利用repo从远程服务器上取代码时候,出现错误  fatal: cannot make .repo directory:Permission denied, 加了sudo 之后,还是不行, ...

  6. HDU 3247 Resource Archiver(AC自动机 + 状压DP + bfs预处理)题解

    题意:目标串n( <= 10)个,病毒串m( < 1000)个,问包含所有目标串无病毒串的最小长度 思路:貌似是个简单的状压DP + AC自动机,但是发现dp[1 << n][ ...

  7. 深入理解JavaScript垃圾回收

    JavaScript中的垃圾回收是自动进行的,在平常开发中我们可能并不在意,但是深入理解JavaScript中的垃圾回收却是必要的; JavaScript 中主要的内存管理概念是 可达性,简而言之就是 ...

  8. Java 对象的哈希值是每次 hashCode() 方法调用重计算么?

    对于没有覆盖hashCode()方法的对象 如果没有覆盖 hashCode() 方法,那么哈希值为底层 JDK C++ 源码实现,实例每次调用hashcode()方法,只有第一次计算哈希值,之后哈希值 ...

  9. config file language All In One

    config file language All In One YAML YAML Ain't Markup Language .yaml / .yml https://yaml.org/ https ...

  10. Prometheus Monitoring Solution

    Prometheus Monitoring Solution 普罗米修斯 https://prometheus.io/ 警报 监控 增强指标和警报 领先 开源监控解决方案 https://promet ...