首页 > 编程语言 >c# HttpClient post get 同步调用

c# HttpClient post get 同步调用

时间:2022-12-02 19:23:48浏览次数:42  
标签:string get c# client var new post Authorization HttpClient

/// <summary>
        /// 发起GET同步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public string HttpGet(string url, string Authorization = "")
        {
            var result = AsyncUtil.RunSync(async () =>
            {
                using (HttpClient client = new HttpClient())
                {
                    if (!string.IsNullOrEmpty(Authorization))
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Authorization);
                    }
                    client.Timeout = new TimeSpan(0, 0, 10);
                    var response = await client.GetAsync(url);
                    return await response.Content.ReadAsStringAsync();
                }
            });
            return result;
        } 

        /// <summary>
        /// 发起POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public string HttpPost(string url, object obj, string Authorization = "")
        {
            var result = AsyncUtil.RunSync(async () =>
            {
                HttpClient client = new HttpClient();
                var json = JsonConvert.SerializeObject(obj);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                if (!string.IsNullOrEmpty(Authorization))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Authorization);
                }
                client.Timeout = new TimeSpan(0, 0, 10);
                var response = await client.PostAsync(url, content);
                return await response.Content.ReadAsStringAsync();
            });
            return result;
        }




////------------------------------------------------------------
public static class AsyncUtil
    {
        private static readonly TaskFactory _taskFactory =
                new TaskFactory(CancellationToken.None,
                        TaskCreationOptions.None,
                        TaskContinuationOptions.None,
                        TaskScheduler.Default);

        /// <summary>
        /// Executes an async Task method which has a void return value synchronously
        /// USAGE: AsyncUtil.RunSync(() => AsyncMethod());
        /// </summary>
        public static void RunSync(Func<Task> task)
            => _taskFactory
                .StartNew(task)
                .Unwrap()
                .GetAwaiter()
                .GetResult();

        /// <summary>
        /// Executes an async Task<T> method which has a T return type synchronously
        /// USAGE: T result = AsyncUtil.RunSync(() => AsyncMethod<T>());
        /// </summary>
        public static TResult RunSync<TResult>(Func<Task<TResult>> task)
            => _taskFactory
                .StartNew(task)
                .Unwrap()
                .GetAwaiter()
                .GetResult();
    }

  

标签:string,get,c#,client,var,new,post,Authorization,HttpClient
From: https://www.cnblogs.com/Gold-fangjin/p/16945403.html

相关文章

  • CSS3 filter(滤镜) 属性使用整理
    一、CSS3filter(滤镜) 1.定义filter属性定义了元素(通常是<img>)的可视效果(例如:模糊与饱和度)。默认值:none继承:no动画支持:是。详细可查阅 CSS动画......
  • ConfigMap/Secret:怎样配置、定制应用(chrono《kubernetes入门实战课》笔记整理)
     【概念说明】Kubernetes里专门用来管理配置信息的两种对象:ConfigMap和Secret,使用它们来灵活地配置、定制我们的应用。配置根据数据安全划分,分为两种:明文配置:不加密......
  • day03--Scanner用户交互
    用户交互Scanner对象基本语法Scanners=newScanner(System.in);通过Scanner类的next()与nextLine()方法获取输入的字符串,再读取前我们一般需要使用hasNext()与ha......
  • 前端CSS学习(二)
    目录边框画圆小例子displaydisplay属性盒子模型浮动溢出overflow溢出属性圆形头像示例定位fixedz-index顶部导航栏代码展示简易博客页面搭建边框<head><metacharse......
  • 前端 css
    目录今日内容概要今日内容详细边框display盒子模型浮动溢出定位z-index简易博客页面搭建今日内容概要边框盒子模型浮动定位补充说明简易博客页面搭建今日内容详......
  • vmware workstation SCSI磁盘格式虚拟机迁移到KVM之后无法启动的问题解决办法
    原文链接:https://blog.51cto.com/duron/2125821转换磁盘镜像格式之后导入KVM系统无法启动,但是可以进入恢复模式,可能是virtio的内核模块没有加载,把磁盘改为IDE模式后正常......
  • CentOS Linux 的安装
    CentOSLinux的安装作者:Grey原文地址:博客园:CentOSLinux的安装CSDN:CentOSLinux的安装说明本安装说明是基于Windows10下VMwareworkstation16安装Linux,Li......
  • 全局zomm缩放后echarts鼠标偏移的问题(鼠标触发提示框位置有偏差)
    <template><divref="chart"class="echarts-con":style="{'zoom':zoom}"></div></template><script>import*asechartsfrom'echarts'//import{EleResize......
  • [C#] Func、Action的简单使用
    参考代码:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;namespaceFuncActionDemo{classFuncActionTest{publicvoidTe......
  • css基础操作2
    今日内容总结边框/*border-left-width:边框大小(px);*//*border-left-style:边框格式;*//*border-left-color:颜色选择*/简写:border-left:边框大小边框格式......