排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
原
.NET HttpClient和webapi相关的东东先记录一点。传递Authorization header,token
分类:
.NET
get请求传递Authorization header,token
string url = "你请求的url"; string token = "your token"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); string result = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
Post,FormUrlEncodedContent传递参数
public static void Main() { HttpClient client = new HttpClient(); List<KeyValuePair<string, string>> kvlist = new List<KeyValuePair<string, string>>(); kvlist.Add(new KeyValuePair<string, string>("aa", "a")); kvlist.Add(new KeyValuePair<string, string>("bb", "x")); HttpContent content = new FormUrlEncodedContent(kvlist); string result = client.PostAsync("http://localhost:8099/api/xx", content).Result.Content.ReadAsStringAsync().Result; }
Post,StringContent传递参数:
public static void Main() { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent strcontent = new StringContent(JsonConvert.SerializeObject(new { aa = "a", bb = "x" }), Encoding.UTF8, "application/json"); string result = client.PostAsync("http://localhost:8099/api/xx", strcontent).Result.Content.ReadAsStringAsync().Result; Console.ReadLine(); }
Post,StringContent传递参数,Json参数,传递header,token
和上面那个其实是一样的,就多传递了一个token
public void SendMail() { string token = "你的token"; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); var content = new { fromPerson = "发件人", mailTitle = "标题", mailBody = "正文内容", recipientArry = new List<string>() { "收件人1@qq.com", "收件人2@qq.com" }, }; StringContent strcontent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json"); string result = client.PostAsync("http://localhost:59154/api/SendMail", strcontent).Result.Content.ReadAsStringAsync().Result; }
简单封装一下,带token的get与post请求
代码如下:
public class RequestTools { /// <summary> /// 封装通用的get请求 /// </summary> /// <param name="baseAddress"></param> /// <param name="token"></param> /// <param name="url"></param> /// <returns></returns> public string Get(string baseAddress, string token, string url) { string questUrl = baseAddress + url; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); string result = client.GetAsync(questUrl).Result.Content.ReadAsStringAsync().Result; return result; } /// <summary> /// 封装通用的Post请求 /// </summary> /// <param name="baseAddress"></param> /// <param name="token"></param> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public string Post(string baseAddress, string token, string url,object data) { string questUrl = baseAddress + url; HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); StringContent strcontent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); string result = client.PostAsync(questUrl, strcontent).Result.Content.ReadAsStringAsync().Result; return result; } }
使用封装get请求:
public override async Task OnStart(JobContext jobContext) { // 从配置文件获取请求接口的基础地址 string baseAddress = SmartEDU.Utils.Appsettings.Configuration["ApiVisit:Address"]; // 获取token TokenTools tokenTools = new TokenTools(); string token = await tokenTools.GetToken(jobContext); // 通过工具类调用接口,并拿到返回数据后反序列化解析成需要的类 RequestTools requestTools = new RequestTools(); // 如果是本地接口的测试可以把baseAddress换成本地地址即可,比如:"http://localhost:8805" string prodResult = requestTools.Get(baseAddress, token, "/prodedu/api/Report/GetYesterdayProjectAbnormal"); BaseApiWrapDto<ProjectExamineDto> projectExamineDto = JsonConvert.DeserializeObject<BaseApiWrapDto<ProjectExamineDto>>(prodResult); }
使用封装的post请求:
public override async Task OnStart(JobContext jobContext) { // 从配置文件获取请求接口的基础地址,一般都是配置域名或者内部ip等 string baseAddress = SmartEDU.Utils.Appsettings.Configuration["ApiVisit:Address"]; // 获取token TokenTools tokenTools = new TokenTools(); string token = await tokenTools.GetToken(jobContext); // 通过工具类调用接口 RequestTools requestTools = new RequestTools(); // 构建好接口需要的参数 var data = new { stdetailID = "3d6717e7300246249c260d18cc9b0279", PageIndex = 1, PageSize = 999, Orders = new List<object>() { new { OrderField = "teacherNames", IsDesc=true } }, }; string prodResult = requestTools.Post(baseAddress, token, "/labroom/api/Report/GetSchoolClassOrCourseDataGather", data); }
post请求接收方的方法定义(这里的测试接口没有使用标准的restful定义,用restful标准定义的接口一样的不影响):
[HttpPost] public ObjectResult GetSchoolClassOrCourseDataGather([FromBody] QuerSchoolLabDTO query) { //换成AJ封装的方法 return Success(rs.GetSchoolTeacherDataGather(query)); }
接收实体QuerSchoolLabDTO的定义:
public class QuerSchoolLabDTO: QueryBase { public string stdetailID { get; set; } /// <summary> /// 0:课程数据,1:班级数据 /// </summary> public int dataType { get; set; } /// <summary> /// 多字段排序 /// </summary> public List<OrderInfo> orders { get; set; } } /// <summary> /// 排序字段 /// </summary> public class OrderInfo { /// <summary> /// 排序字段 /// </summary> public string OrderField { get; set; } /// <summary> /// 是否为降序 /// </summary> public Boolean IsDesc { get; set; } }
webapi中这样写可以接收到httpclient传递的参数
JObject是Newtonsoft.Json.Linq下面的。当然这种传递参数的写法,使用对象接收也是能接收到的比如:[FromBody] Mail mails
设置类型还可以直接点出来设置
strcontent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); strcontent.Headers.ContentType.CharSet = "utf-8";
HttpClient手动传递cookie信息
//获取cookie的token信息 string token; HttpContext.Request.Cookies.TryGetValue("token", out token); //发送请求携带token HttpClient httpClient = new HttpClient(); var message = new HttpRequestMessage(HttpMethod.Post, "http://localhost:X5J/api/v1/Token"); message.Headers.Add("Cookie", "token=" + token); var httpResponseHeaders = httpClient.SendAsync(message).Result;
如果是请求了一遍想要自带cookie的话可以这样做
HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent strcontent = new StringContent(JsonConvert.SerializeObject("aa"), Encoding.UTF8, "application/json"); var message = new HttpRequestMessage(HttpMethod.Post, "your address"); //设置cookie信息 message.Headers.Add("Cookie", "token=" + token); //设置contetn message.Content = strcontent; //发送请求 var httpResponseHeaders = httpClient.SendAsync(message).Result;
一个简单的get请求示例
/// <summary> /// HttpClient实现Get请求 /// </summary> static async void dooGet() { string url = "http://localhost:52824/api/register?id=1&leval=5"; //创建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()); } }
传递参数的同时传递一个cookie
https://www.tnblog.net/aojiancc2/article/details/3834
c# HttpClient 给webapi post传递一个参数
https://www.tnblog.net/aojiancc2/article/details/3834
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价