本文章是在VS2017的环境下,.net core 1.1版本以上。
在这期间,由于.net core 并不基于IIS,我们的过去的网络请求代码在.net core框架下,有可能会出现不兼容,报错的现象。这里大致介绍下在.net core 下如何进行http请求,主要仍然是GET和POST方法,有错误的地方,欢迎指正!
先来说POST,POST我实现了三种方法,前两种基于的原理是完全一致的,后面的有些小小的差异,但他们的本质都是http请求,本质上是无区别的,只是实现方法有所不同。
废话不多说,上代码:
POST异步方法:
/// <summary> /// 异步请求post(键值对形式,可等待的) /// </summary> /// <param name="uri">网络基址("http://localhost:59315")</param> /// <param name="url">网络的地址("/api/UMeng")</param> /// <param name="formData">键值对List<KeyValuePair<string, string formData = new List<KeyValuePair<string, string();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">编码格式</param> /// <param name="mediaType">头媒体类型</param> /// <returns></returns> public async Task<string> HttpPostAsync(string uri, string url, List<KeyValuePair<string, string formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } HttpResponseMessage resp = await client.PostAsync(tokenUri, content); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }
POST同步方法:
/// <summary> /// 同步请求post(键值对形式) /// </summary> /// <param name="uri">网络基址("http://localhost:59315")</param> /// <param name="url">网络的地址("/api/UMeng")</param> /// <param name="formData">键值对List<KeyValuePair<string, string formData = new List<KeyValuePair<string, string();formData.Add(new KeyValuePair<string, string>("userid", "29122"));formData.Add(new KeyValuePair<string, string>("umengids", "29122"));</param> /// <param name="charset">编码格式</param> /// <param name="mediaType">头媒体类型</param> /// <returns></returns> public string HttpPost(string uri, string url, List<KeyValuePair<string, string formData = null, string charset = "UTF-8", string mediaType = "application/x-www-form-urlencoded") { string tokenUri = url; var client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpContent content = new FormUrlEncodedContent(formData); content.Headers.ContentType = new MediaTypeHeaderValue(mediaType); content.Headers.ContentType.CharSet = charset; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } var res = client.PostAsync(tokenUri, content); res.Wait(); HttpResponseMessage resp = res.Result; var res2 = resp.Content.ReadAsStringAsync(); res2.Wait(); string token = res2.Result; return token; }
遗憾的是,同步方法也是基于异步实现的,个人认为这样做会加大系统开销。如果各位有其他的高效实现,请不吝赐教!
接下来是通过流的方式进行POST:
public string Post(string url, string data, Encoding encoding, int type) { try { HttpWebRequest req = WebRequest.CreateHttp(new Uri(url)); if (type == 1) { req.ContentType = "application/json;charset=utf-8"; } else if (type == 2) { req.ContentType = "application/xml;charset=utf-8"; } else { req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; } req.Method = "POST"; //req.Accept = "text/xml,text/javascript"; req.ContinueTimeout = 60000; byte[] postData = encoding.GetBytes(data); Stream reqStream = req.GetRequestStreamAsync().Result; reqStream.Write(postData, 0, postData.Length); reqStream.Dispose(); var rsp = (HttpWebResponse)req.GetResponseAsync().Result; var result = GetResponseAsString(rsp, encoding); return result; } catch (Exception ex) { throw; } }
private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Dispose(); if (stream != null) stream.Dispose(); if (rsp != null) rsp.Dispose(); } }
这种方式的POST还是将数据写入到流里面,进行POST,之所以写前两个key-value的形式,是为了符合java或者oc的风格,在c#书写的webapi中,由于接收形式是{=value}而不是{key=value}(由webapi的性质决定),后续我会说如何在webapi中接收(key-value)的形式,适当避免.net后台人员与android和ios的矛盾,从而达到社会主义民主社会的长治久安。
接下来是get,同样同步异步都是由异步实现的,还请各位看官轻喷。
GET:
/// <summary> /// 异步请求get(UTF-8) /// </summary> /// <param name="url">链接地址</param> /// <param name="formData">写在header中的内容</param> /// <returns></returns> public static async Task<string> HttpGetAsync(string url, List<KeyValuePair<string, string formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get, }; for (int i = 0; i < formData.Count; i++) { request.Headers.Add(formData[i].Key, formData[i].Value); } var resp = await httpClient.SendAsync(request); resp.EnsureSuccessStatusCode(); string token = await resp.Content.ReadAsStringAsync(); return token; }
/// <summary> /// 同步get请求 /// </summary> /// <param name="url">链接地址</param> /// <param name="formData">写在header中的键值对</param> /// <returns></returns> public string HttpGet(string url, List<KeyValuePair<string, string formData = null) { HttpClient httpClient = new HttpClient(); HttpContent content = new FormUrlEncodedContent(formData); if (formData != null) { content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); content.Headers.ContentType.CharSet = "UTF-8"; for (int i = 0; i < formData.Count; i++) { content.Headers.Add(formData[i].Key, formData[i].Value); } } var request = new HttpRequestMessage() { RequestUri = new Uri(url), Method = HttpMethod.Get, }; for (int i = 0; i < formData.Count; i++) { request.Headers.Add(formData[i].Key, formData[i].Value); } var res = httpClient.SendAsync(request); res.Wait(); var resp = res.Result; Task<string> temp = resp.Content.ReadAsStringAsync(); temp.Wait(); return temp.Result; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 《怪猎荒野》PS5Pro主机版对比:B测性能都不稳定
- 黄宝欣.1992-黄宝欣金装精选2CD【HOMERUN】【WAV+CUE】
- 群星.1996-宝丽金流行爆弹精丫宝丽金】【WAV+CUE】
- 杜德伟.2005-独领风骚新歌精选辑3CD【滚石】【WAV+CUE】
- 安与骑兵《心无疆界》[低速原抓WAV+CUE]
- 柏菲唱片-群星〈胭花四乐〉2CD[原抓WAV+CUE]
- 金典女声发烧靓曲《ClassicBeautifulSound》2CD[低速原抓WAV+CUE]
- 王杰1992《封锁我一生》粤语专辑[WAV+CUE][1G]
- 群星《一人一首成名曲 (欧美篇)》6CD[WAV/MP3][7.39G]
- 东来东往2004《回到我身边·别说我的眼泪你无所谓》先之唱片[WAV+CUE][1G]
- MF唱片-《宝马[在真HD路上]》2CD[低速原抓WAV+CUE]
- 李娜《相信我》新时代[WAV+CUE]
- 2019明达发烧碟MasterSuperiorAudiophile[WAV+CUE]
- 蔡幸娟.1993-相爱容易相处难【飞碟】【WAV+CUE】
- 陆虎.2024-是否愿意成为我的全世界【Hikoon】【FLAC分轨】