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(); }
本文来自博客园,作者:方金,转载请注明原文链接:https://www.cnblogs.com/Gold-fangjin/p/16945403.html