c# HttpClient post get 同步调用

/// <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();
    }

  

posted @ 2022-12-02 19:08  方金  阅读(1180)  评论(0编辑  收藏  举报