c# 【MVC】WebApi通过HttpClient来调用Web Api接口
2016-06-08 15:41
543 查看
/// <summary> /// HttpClient实现Post请求(异步) /// </summary> static async void dooPost() { string url = "http://localhost:52824/api/register"; //设置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //创建HttpClient(注意传入HttpClientHandler) using (var http = new HttpClient(handler)) { //使用FormUrlEncodedContent做HttpContent var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"Id","6"}, {"Name","添加zzl"}, {"Info", "添加动作"}//键名必须为空 }); //await异步等待回应 var response = await http.PostAsync(url, content); //确保HTTP成功状态值 response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } } /// <summary> /// HttpClient实现Get请求(异步) /// </summary> static async void dooGet() { string url = "http://localhost:52824/api/register?id=1"; //创建HttpClient(注意传入HttpClientHandler) var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var http = new HttpClient(handler)) { //await异步等待回应 var response = await http.GetAsync(url); //确保HTTP成功状态值 response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } } /// <summary> /// HttpClient实现Put请求(异步) /// </summary> static async void dooPut() { var userId = 1; string url = "http://localhost:52824/api/register?userid=" + userId; //设置HttpClientHandler的AutomaticDecompression var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; //创建HttpClient(注意传入HttpClientHandler) using (var http = new HttpClient(handler)) { //使用FormUrlEncodedContent做HttpContent var content = new FormUrlEncodedContent(new Dictionary<string, string>() { {"Name","修改zzl"}, {"Info", "Put修改动作"}//键名必须为空 }); //await异步等待回应 var response = await http.PutAsync(url, content); //确保HTTP成功状态值 response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) Console.WriteLine(await response.Content.ReadAsStringAsync()); } }
相关文章推荐
- OSI七层与TCP/IP五层网络架构详解
- OSI七层与TCP/IP五层网络架构详解
- tcpdump 抓包工具
- Tomcat生成https+ssl双向证书认证
- netstat –lnp查看监听端口(查看网络连接状况)
- android6.0SDK中删除HttpClient的相关类的解决方法
- 【安卓SDK学习之anyChatSDK】 1_1 实现用户登录和房间进出(根据官方HelloAnyChat的demo整理的简要的开发流程)
- 处理 httprequest post 编码问题
- 重头再来
- HDU 4780 Candy Factory(网络流)
- HTTPS
- Xcode7 使用NSURLSession发送HTTP请求的问题
- Java客户端利用httpclient来同时上传文件和其他字符串参数
- http post
- HTTP协议详解
- HTML——HTTP
- HTTP状态码大全
- 网络LED矩阵显示器
- 理解HTTP幂等性
- linux网络编程常用头文件总结