后台调用 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 几种方式的更多相关文章
- DLL调用的两种方式(IDE:VC6.0,C++)
原文:http://www.cnblogs.com/Pickuper/articles/2050409.html DLL调用有两种方式,一种是静态调用,另外一种是动态调用 (一)静态调用 静态调用是一 ...
- java后台输入数据的2种方式
java后台输入数据的2种方式 (1) import java.io.BufferedReader; import java.io.InputStreamReader; public class 输入 ...
- python 模块调用的几种方式
在python里面又很多模块,或者引用第三方模块,python 模块调用的几种方式,下面详细解说 1,import 模块名 2,from 模块 import 模块里面的小功能 3,from 模块 ...
- [OpenSource]浅谈.Net和Java互相调用的三种方式
在很多的大型系统开发中,开发工具往往不限制于同一种开发语言,而是会使用多种开发语言的混合型开发.目前Java和.Net都声称自己占85%的市场份额,不管谁对谁错,Java和.Net是目前应用开发的两个 ...
- 浅谈.Net和Java互相调用的三种方式
在很多的大型系统开发中,开发工具往往不限制于同一种开发语言,而是会使用多种开发语言的混合型开发.目前Java和.Net都声称自己占85%的市场份 额,不管谁对谁错,Java和.Net是目前应用开发的两 ...
- Struts2方法调用的三种方式
在Struts2中方法调用概括起来主要有三种形式 第一种方式:指定method属性 <action name="student" class="com.itmyho ...
- springcloud 服务调用的两种方式
spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign.Ribbon是一个基于HTTP和TCP客户端的负载均衡器,其实feign也使用了rib ...
- SpringBoot2.0.2 Application调用的三种方式
一.注解 @SpringBootApplication 点开查看源码是由多个注解合成的注解,其中主要的注解有: @SpringBootConfigurati ...
- Struts2方法调用的三种方式(有新的!调用方法的说明)
在Struts2中方法调用概括起来主要有三种形式 第一种方式:指定method属性 <action name="heroAction" class="com.ABC ...
- 使用RestTemplate进行服务调用的几种方式
首先我们在名为MSG的服务中定义一个简单的方法 @RestController public class ServerController { @GetMapping("/msg" ...
随机推荐
- raise EOFError("Compressed file ended before the " EOFError: Compressed file ended before the end-of-stream marker was reached
参考: EOFError: Compressed file ended before the end-of-stream marker was reached解决办法(在Windows下查看已下载的M ...
- 使用python启动appium(虚拟器)
1.先安装各种库 https://www.cnblogs.com/zhanglingling00/p/14169462.html pip install Appium-Flutter-Finder p ...
- C#中DataTable新增列、删除列、更改列名、交换列位置
一.新增列 1.1.新增列 /*新增列*/ dataTable.Columns.Add("列名称", Type.GetType("数据类型")); /*比如添加 ...
- 蓝桥杯训练赛二-问题 B
字符串的输入输出处理. 输入 第一行是一个正整数N,最大为100.之后是多行字符串(行数大于N), 每一行字符串可能含有空格,字符数不超过1000. 输出 先将输入中的前N行字符串(可能含有空格)原样 ...
- 解决ubuntu18环境matplotlib无法正常显示中文
首先看看系统装了中文字体没?命令: fc-list :lang=zh 如果没安装,需要去下载或者从win复制一份到ubuntu, 在/usr/share/fonts文件夹下创建一个chinese文件夹 ...
- testtesttest
test test 2022-09-24 #include<iostream> using namespace std; int main(){ cout<<&qu ...
- [USACO12FEB]Overplanting S
洛咕 题意:在一个笛卡尔平面坐标系里(X轴向右是正方向,Y轴向上是正方向),有\(N(1<=N<=1000)\)个矩形,第\(i\)个矩形的左上角坐标是\((x1, y1)\),右下角坐标 ...
- Linux 系统jdk安装详细教程
安装jdk步骤先下载jdk的tar压缩包然后解压jdk并压缩至指定安装目录,如果不需要指定安装目录直接写tar -zxvf jdk压缩包名即可tar -zxvf jdk压缩包 -C /这里写指定安装目 ...
- HiveServer2启动报TezConfiguration类NoClassDefFoundError错误
错误信息如下: 2021-01-03 20:11:26,355 WARN [main] server.HiveServer2: Error starting HiveServer2 on attemp ...
- tiktok运营工具
1.自信点!这就是TikTok最全运营工具合集! - 知乎 (zhihu.com) 2.骄傲的和大家说!这就是TikTok最全运营工具合集! - 知乎 (zhihu.com) 3.如何批量去水印下载抖 ...