博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient PostAsync/GetAsync JSON Example
阅读量:6070 次
发布时间:2019-06-20

本文共 2430 字,大约阅读时间需要 8 分钟。

PostAsync

static readonly HttpClient Client = new HttpClient();public async Task
PostAsync
(string url, object data) where T : class, new(){ try { string content = JsonConvert.SerializeObject(data); var buffer = Encoding.UTF8.GetBytes(content); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await Client.PostAsync(url, byteContent).ConfigureAwait(false); string result = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { logger.Error($"GetAsync End, url:{url}, HttpStatusCode:{response.StatusCode}, result:{result}"); return new T(); } logger.Info($"GetAsync End, url:{url}, result:{result}"); return JsonConvert.DeserializeObject
(result); } catch (WebException ex) { if (ex.Response != null) { string responseContent = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); throw new System.Exception($"response :{responseContent}", ex); } throw; }}

  

GetAsync

static readonly HttpClient Client = new HttpClient();public async Task
GetAsync(string url, object data){ try { string requestUrl = $"{url}?{GetQueryString(data)}"; logger.Info($"GetAsync Start, requestUrl:{requestUrl}"); var response = await Client.GetAsync(requestUrl).ConfigureAwait(false); string result = await response.Content.ReadAsStringAsync(); logger.Info($"GetAsync End, requestUrl:{requestUrl}, HttpStatusCode:{response.StatusCode}, result:{result}"); return result; } catch (WebException ex) { if (ex.Response != null) { string responseContent = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); throw new Exception($"Response :{responseContent}", ex); } throw; }}private static string GetQueryString(object obj){ var properties = from p in obj.GetType().GetProperties() where p.GetValue(obj, null) != null select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(obj, null).ToString()); return String.Join("&", properties.ToArray());}

  

转载于:https://www.cnblogs.com/XuPengLB/p/10860949.html

你可能感兴趣的文章
复杂业务下,我们为何选择Akka作为异步通信框架?
查看>>
边缘控制平面Ambassador全解读
查看>>
Windows Phone 7 利用计时器DispatcherTimer创建时钟
查看>>
程序员最喜爱的12个Android应用开发框架二(转)
查看>>
vim学习与理解
查看>>
DIRECTSHOW在VS2005中PVOID64问题和配置问题
查看>>
MapReduce的模式,算法以及用例
查看>>
《Advanced Linux Programming》读书笔记(1)
查看>>
zabbix agent item
查看>>
一步一步学习SignalR进行实时通信_7_非代理
查看>>
AOL重组为两大业务部门 全球裁员500人
查看>>
字符设备与块设备的区别
查看>>
为什么我弃用GNOME转向KDE(2)
查看>>
Redis学习记录初篇
查看>>
爬虫案例若干-爬取CSDN博文,糗事百科段子以及淘宝的图片
查看>>
Web实时通信技术
查看>>
第三章 计算机及服务器硬件组成结合企业运维场景 总结
查看>>
IntelliJ IDEA解决Tomcal启动报错
查看>>
默认虚拟主机设置
查看>>
七周五次课(1月26日)
查看>>