public class HttpClientBase
{ /// <summary>
/// HttpClient实现Post请求
/// </summary> protected async Task<object> dooPost(string url, Dictionary<string, string> dic)
{ //设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(dic);
//await异步等待回应
var response = await http.PostAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
string Result = await response.Content.ReadAsStringAsync(); var Item = JsonConvert.DeserializeObject(Result); return Item;
}
} /// <summary>
/// HttpClient实现Get请求
/// </summary>
protected async Task<object> dooGet(string url)
{ //创建HttpClient(注意传入HttpClientHandler)
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
string Result = "";
using (var http = new HttpClient(handler))
{
//await异步等待回应
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
Result = await response.Content.ReadAsStringAsync(); var Items= JsonConvert.DeserializeObject(Result); return Items;
}
} /// <summary>
/// HttpClient实现Put请求
/// </summary>
protected async Task<object> dooPut(string url, Dictionary<string, string> dic)
{ //设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
string Result="";
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(dic);
//await异步等待回应
var response = await http.PutAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
JavaScriptSerializer Serializer = new JavaScriptSerializer();
var items = Serializer.DeserializeObject(Result);
return items;
} } /// <summary>
/// HttpClient实现Get请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
protected object doGet(string url)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync(url).Result; // Blocking call(阻塞调用)! var result = ""; if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result; JavaScriptSerializer Serializer = new JavaScriptSerializer();
var items = Serializer.DeserializeObject(result);
return items;
}
return result;
} /// <summary>
/// HttpClient实现Post请求
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
protected object doPost(string url, Dictionary<string, string> dic,ref string StatusCode)
{ HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url); JavaScriptSerializer jss = new JavaScriptSerializer(); var content = new FormUrlEncodedContent(dic);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.PostAsync(url, content).Result;
var result = "";
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result; JavaScriptSerializer Serializer = new JavaScriptSerializer();
var items = Serializer.DeserializeObject(result);
//Dictionary<string, object> jarry = (Dictionary<string, object>)items;
//obj ss = jarry["IsSuccess"];
//string sate = jarry[0]["IsSuccess"].ToString();
return items;
}else
{
StatusCode = response.StatusCode.ToString(); ;
}
return result;
} /// <summary>
/// 转换URL
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string UrlEncode(string str)
{
StringBuilder sb = new StringBuilder();
byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str);
for (int i = 0; i < byStr.Length; i++)
{
sb.Append(@"%" + Convert.ToString(byStr[i], 16));
}
return (sb.ToString());
}
}

WebApi帮助类的更多相关文章

  1. C# HttpClient请求Webapi帮助类

    引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...

  2. HTTPClick调用WebApi帮助类

    1.创建ApiHelper类 2.复制以下代码到类中 using System; using System.Collections.Generic; using System.Linq; using ...

  3. 封装WebAPI客户端,附赠Nuget打包上传VS拓展工具

    一.前言 上篇< WebAPI使用多个xml文件生成帮助文档 >有提到为什么会出现基于多个xml文件生成帮助文档的解决方案,因为定义的模型可能的用处有: 1:单元测试 2:其他项目引用(可 ...

  4. WebApi个人理解概要

    WebApi概要 Global文件的作用: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class MvcApplication : System.We ...

  5. WebAPI客户端

    封装WebAPI客户端,附赠Nuget打包上传VS拓展工具 一.前言 上篇< WebAPI使用多个xml文件生成帮助文档 >有提到为什么会出现基于多个xml文件生成帮助文档的解决方案,因为 ...

  6. WebApi实现原理解析笔记

    这是我看过WebApi实现代码后的一些总结,一方面加深自己的记忆,另外也希望能够帮助大家更深入的了解WebApi. 注:暂时没有好好的整理,可能有些晦涩难懂. Webapi 控制器类必须实现IHttp ...

  7. webapi框架搭建-依赖注入之autofac

    前言 c#的依赖注入框架有unity.autofac,两个博主都用过,感觉unity比较简单而autofac的功能相对更丰富(自然也更复杂一点),本篇将基于前几篇已经创建好的webapi项目,引入au ...

  8. webapi框架搭建-创建项目(三)-webapi owin

    上一篇:创建项目(二) 在上一篇里,我们已经创建好了webapi应用,并已经部署到iis里,本篇讲如何用owin自宿主或是iis宿主来部署webapi应用. owin介绍 传统的asp.net网站只能 ...

  9. mvc接口、webapi、webservice 对比

    最近做了很多项目,也同时使用了mvc的接口,webapi的接口,以及webservice 的接口.先两两对比如下: mvc和webapi区别: 1.MVC是建站的一种框架,倾向于返回用户的页面请求:a ...

随机推荐

  1. MySQL5.7安装(RPM)笔记

    1. 检查MySQL是否安装,如果有安装,则移除(rpm –e 名称)[root@localhost ~]# rpm -qa | grep -i mysqlmysql-libs-xxxxxxxxxx. ...

  2. 51nod 1463 找朋友 (扫描线+线段树)

    1463 找朋友  基准时间限制:1.5 秒 空间限制:262144 KB 分值: 80 难度:5级算法题  收藏  关注 给定: 两个长度为n的数列A .B 一个有m个元素的集合K 询问Q次 每次询 ...

  3. HGOI2010816 (NOIP 提高组模拟赛 day1)

    Day1 210pts(含T1莫名的-10pts和T3莫名的-30pts) 100+70+40=210 rank 29 这道题第一眼看是字符串匹配问题什么KMP啊,又想KMP不会做啊,那就RK Has ...

  4. Linux系统Web网站目录和文件安全权限设置

    查看Linux文件的权限:ls -l 文件名称查看linux文件夹的权限:ls -ld 文件夹名称(所在目录)例如: drwxr-xr-x 2 root root 4096 2009-01-14 17 ...

  5. 用HashSet存储不重复的对象

    直接进入主题,先来创建一个类:Bean public class Bean { private int id; private String name; public Bean() { super() ...

  6. php错误日志

    php错误日志 /usr/local/php/var/log/php-fpm.log」—————————

  7. 在同一个表中将varchar2类型的数据转存到blob类型的字段中

    用一条修改语句即可:update t_content set f_body=rawtohex(f_check) where f_type in (0,4)此处须用rawtohex()函数将f_chec ...

  8. jeesite快速开发平台---数据库各表一览

    jeesite中一共有55张表,如下 其中以act_*开头的是Activity工作流的表,cms_*开头的是内容管理系统的表,oa_*开头的是办公自动化,sys_*开头的是系统表,test_*开头的是 ...

  9. 深入分析Java Web技术内幕

    深入web请求过程 发起一个http请求的过程就是建立一个socket通信的过程 HTTPClient是一个开源的实现了http请求的工具包 深入分析java I/O的工作机制 深入分析java We ...

  10. Sublime Text 3 绿色汉化版 x64

    之前做了<Sublime Text 2 绿色汉化版 x64>,这些天抽空做了下 ST3 的汉化.. 果然我没有任何理由爱上 ST3,不仅pojie麻烦,而且汉化更麻烦,菜单字符长度做了限制 ...