ZHI.ZSystem开发组件介绍之发送HTTP请求

ZHI.ZSystem是github上一款开源的帮助函数库。其针对.NET System库内部对象实现了大量的扩展方法,同时还集成了超级多的帮助类,以便于我们日常编程开发。最重要的是它基于.NET Standard 2.0目标框架编写,.NET Core 与.NET Framework编码工程师们都可以使用,不用根据版本下载,是不是超赞!

GitHub地址:https://github.com/peashooters/zhi

Gitee地址:https://gitee.com/peashooters/zhi

官方文档:https://peashooters.gitee.io/zhi-doc

今天要介绍的是发起http请求的帮助类HttpHelper,其主要作用是发起http请求,接下来我们用一段代码来展示它的用法:

//HTTP GET 请求
var taobao = "https://suggest.taobao.com/sug";
var timestamp = DateTime.Now.ToUtcTimeStamp(TimeStampUnit.Millisecond);//ZHI.ZSystem内置扩展函数
var httpResponse = string.Empty;
//参数q:表示查询关键词
//参数_:当前时间戳
var parameters = "code=utf-8&q=笔&extras=1area=c2c&bucketid=atb_searchpid=mm_26632258_3504122_32538762&unid=&clk1=3316c22850177cb5649f1a983455721b&callback=jsonp4&_=" + timestamp.ToString();
var url = string.Format("{0}?{1}", taobao, parameters);
httpResponse = HttpHelper.HttpGet(url);
Console.WriteLine("请求结果(仅地址):{0}", httpResponse);
Console.WriteLine();
Console.WriteLine();
var header = new Dictionary<string, string>();
header.Add("referer", "https://uland.taobao.com/");
header.Add("authority", "suggest.taobao.com");
httpResponse = HttpHelper.HttpGet(url, header);
Console.WriteLine("请求结果(地址、请求头):{0}", httpResponse);

我们来看一下GET请求结果(地址是淘宝首页的搜索商品):

请求结果(仅地址):
jsonp4({"result":[["笔记本电脑","142067.3502377855"],["笔袋","311787.0411424312"],["笔记本","334875.0280249376"],["笔筒","373780.2144637851"],["笔盒","250278.82041203202"],["笔袋大容量","97785.50406100812"],["笔记本子","47486.52840646651"],["笔芯","271206.81850920705"],["笔记本电脑包","115447.5925248509"],["笔袋ins日系","16469.91278123504"]]})


请求结果(地址、请求头):
jsonp4({"result":[["笔记本电脑","142067.3502377855"],["笔袋","311787.0411424312"],["笔记本","334875.0280249376"],["笔筒","373780.2144637851"],["笔盒","250278.82041203202"],["笔袋大容量","97785.50406100812"],["笔记本子","47486.52840646651"],["笔芯","271206.81850920705"],["笔记本电脑包","115447.5925248509"],["笔袋ins日系","16469.91278123504"]]})

发起POST请求的方法:

//HTTP POST 请求
var baidu = "https://fanyi.baidu.com/langdetect";
var parameters = "query=a";
var httpResponse = string.Empty;
var url = baidu;
//发起请求
httpResponse = HttpHelper.HttpPost(url, parameters);
Console.WriteLine("请求结果(地址、参数):{0}", httpResponse);
Console.WriteLine();
Console.WriteLine();
var header = new Dictionary<string, string>();
header.Add("origin", "https://fanyi.baidu.com");
header.Add("referer", "https://fanyi.baidu.com/");
header.Add("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//发起请求 (携带请求头)
httpResponse = HttpHelper.HttpPost(url, parameters, null, header);
Console.WriteLine("请求结果(地址、参数、请求头):{0}", httpResponse);

看看POST请求结果(地址是百度翻译地址):

请求结果(地址、参数):{"errno":1000,"errmsg":"u672au77e5u9519u8bef"}


请求结果(地址、参数、请求头):{"errno":1000,"errmsg":"u672au77e5u9519u8bef"}

以上就是今天分享的全部内容。看完是不是觉得特别简单呢,不管发送Get请求还是Post请求,都不用实例化请求对象,使用体验超级好。如果有更多想要探讨的问题,还可以加QQ 技术群:735837718(500人上限),欢迎留言到博客或者加群讨论哦~

原文地址:https://www.cnblogs.com/ShentianyinGX/p/14318400.html