HttpHelper
一. HttpHelper介绍:
HttpHelper 基于 netstandard 2.0 开发,支持.net 4.6.1和.net core项目,可以方便开发者发送 get 、post 请求,支持设置 cookie、header、代理等。内置将返回的json字符串转换成对象。
二. 使用
1. 引用nugget包
Sw.Core.HttpHelper
2. Get示例
var http = new HttpHelper(); var item = new HttpItem() { URL = "https://www.baidu.com?name=sw" }; var result = http.GetHtml(item);
3. Post示例
string post = "name=wj"; var http = new HttpHelper(); var item = new HttpItem() { URL = "https://www.baidu.com", Method = "POST", ContentType = "application/x-www-form-urlencoded", Postdata = post, }; var result = http.GetHtml(item);
4. 获取结果的方法:
var result = http.GetHtml(item); result.StatusCode == System.Net.HttpStatusCode.OK
5. 我最近在项目中使用的示例:
Result Outresult = new Result(); WebHeaderCollection headers = new WebHeaderCollection(); //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJOYW1lIjoiVGVzdCIsIlJvbGUiOiJBZG1pbmlzdHJhdG9yIiwiZXhwIjoxNjQzMzY5NzU0LCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjgwODAifQ.NjdyWMattH7scI9fQpCYQIIAI3JjQUsR1hl0klPp174 headers.Add("Authorization: Bearer " + input.token); //var model= _context.InterDetail.Find(input.Id); var model= _context.InterDetail.Find(input.Id); var groupmodel = _context.InterGroup.Find(model.GroupId); string url = groupmodel.Domain + model.Address;// +"?"+ "Scorching=Scorching"; var http = new HttpHelper(); HttpItem item = new HttpItem(); item.Header = headers; item.ContentType = "application/json; charset=utf-8"; if (model.Method == 0) //post { item.Method = "POST"; item.Postdata = model.Param; } else { if(!string.IsNullOrEmpty(model.Param)) { url += "?"+model.Param; } } item.URL = url; //string postdata = "groupName=测试&create_Time=2021-01-21&create_User=wj&Domain=ceshi"; //string postdata= "{\"groupName\":\"测试\",\"create_Time\":\"2021-01-21\",\"create_User\":\"wj\",\"Domain\":\"测试\"}"; //var item = new HttpItem() //{ // //URL = "http://localhost:8000/WeatherForecast", // URL = url, // Header = headers, // Postdata = postdata, // Method="POST", // ContentType = "application/json; charset=utf-8", //}; RunInterResult data = new RunInterResult(); var result = http.GetHtml(item); model.StatusCode = result.StatusCode.ToString(); model.Html = result.Html; _context.InterDetail.Update(model); _context.SaveChanges(); data.StatusCode = result.StatusCode.ToString(); data.Html = result.Html; Outresult.data = data; //var results = http.FastRequest(item); return Outresult;
谢谢学习!!!共同进步