示例是调用谷歌短网址的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. DLL调用的两种方式(IDE:VC6.0,C++)

    原文:http://www.cnblogs.com/Pickuper/articles/2050409.html DLL调用有两种方式,一种是静态调用,另外一种是动态调用 (一)静态调用 静态调用是一 ...

  2. java后台输入数据的2种方式

    java后台输入数据的2种方式 (1) import java.io.BufferedReader; import java.io.InputStreamReader; public class 输入 ...

  3. python 模块调用的几种方式

    在python里面又很多模块,或者引用第三方模块,python 模块调用的几种方式,下面详细解说 1,import 模块名 2,from 模块 import  模块里面的小功能 3,from  模块 ...

  4. [OpenSource]浅谈.Net和Java互相调用的三种方式

    在很多的大型系统开发中,开发工具往往不限制于同一种开发语言,而是会使用多种开发语言的混合型开发.目前Java和.Net都声称自己占85%的市场份额,不管谁对谁错,Java和.Net是目前应用开发的两个 ...

  5. 浅谈.Net和Java互相调用的三种方式

    在很多的大型系统开发中,开发工具往往不限制于同一种开发语言,而是会使用多种开发语言的混合型开发.目前Java和.Net都声称自己占85%的市场份 额,不管谁对谁错,Java和.Net是目前应用开发的两 ...

  6. Struts2方法调用的三种方式

    在Struts2中方法调用概括起来主要有三种形式 第一种方式:指定method属性 <action name="student" class="com.itmyho ...

  7. springcloud 服务调用的两种方式

    spring-cloud调用服务有两种方式,一种是Ribbon+RestTemplate, 另外一种是Feign.Ribbon是一个基于HTTP和TCP客户端的负载均衡器,其实feign也使用了rib ...

  8. SpringBoot2.0.2 Application调用的三种方式

    一.注解 @SpringBootApplication            点开查看源码是由多个注解合成的注解,其中主要的注解有:            @SpringBootConfigurati ...

  9. Struts2方法调用的三种方式(有新的!调用方法的说明)

    在Struts2中方法调用概括起来主要有三种形式 第一种方式:指定method属性 <action name="heroAction" class="com.ABC ...

  10. 使用RestTemplate进行服务调用的几种方式

    首先我们在名为MSG的服务中定义一个简单的方法 @RestController public class ServerController { @GetMapping("/msg" ...

随机推荐

  1. Spring Boot应用启动

    1.Eclipse 中启动Spring Boot应用 右键应用程序启动类, Run As Java Application 2.maven 命令: mvn spring-boot:run 在应用程序启 ...

  2. python代码规范PEP8

    1.引言 本文档给出了 Python 编码规约,主要 Python 发行版中的标准库即遵守该规约.对于 C 代码风格的 Python 程序,请参阅配套的 C 代码风格指南. 本文档和 PEP 257( ...

  3. JAVA仓库管理系统(附源码+调试)

    JAVA仓库管理系统--三只松鼠仓库管理系统功能描述(1)登录模块:登录信息等存储在数据库中(2)基本档案管理模块:供货商管理,销售商管理,货品档案管理,仓库管理(3)采购订货模块:用户可以通过查询条 ...

  4. String.prototype.replace--替换字符串

    str.replace(regexp|substr, newSubStr|function)     API本身不改变原本的字符串,只是返回新的字符串例子:用函数作为第二个参数function rep ...

  5. Dapper.FastCRUD与Dapper中的CustomPropertyTypeMap冲突

    在使用Dapper.NET时,由于生成的实体的属性与数据库表字段不同(如表字段叫USER_NAME,生成的对应的实体属性则为UserName). 这时需要使用Dapper中的CustomPropert ...

  6. oracle 函数instr

  7. 点击div实现选中效果

    先上一份效果图.原来的checked多选框还是存在的,我只不过隐藏了,让他的整个div的范围都是可以点击的,右上角三个点是可以删除当前元素,左下角的播放按钮可以点击播放语音,主要是利用z-index把 ...

  8. Kubernetes--Ingress资源

    Ingress资源 Kubernetes提供了两种内建的云端负载均衡机制(cloud load balancing)用于发布公共应用,一种是工作于传输层的Service资源,它实现的是"TC ...

  9. 【PDF】数理科学 2001年01月号 特集:「時間とは何か」- 時間が生んだ世界観とパラダイム -

    书本详情 标题:数理科学 2001年01月号 特集:「時間とは何か」- 時間が生んだ世界観とパラダイム - | 数理科学編集部 | 年份:2001出版社:サイエンス社ISBN10:暂无信息5ISBN1 ...

  10. 使用signalr不使用连接服务器和前台的js的方法

    1:使用这种方式,,就不需要前后台链接的js 2:新建一个empty的MVC项目 3:新建一个controller和index.html 4: 新建一个signalr 集线器类名为PersonHub, ...