.net HttpClient通用的请求封装 电脑版发表于:2024/9/8 16:16 [TOC] ### 封装的代码如下 ``` /// <summary> /// 通用的请求类封装AJ /// </summary> public class NewRequestTools { /// <summary> /// 当配置中获取的地址为空的时候使用的地址 /// </summary> private string defaultBaseAddress = "https://smartedu-apis.xx.com"; /// <summary> /// 测试地址,方便测试的时候使用比如调试本地接口的时候,又难得去修改配置的情况 /// </summary> private string testBaseAddress = ""; /// <summary> /// 设置默认地址 /// </summary> /// <param name="_baseApi"></param> public void SetDefaultBaseAddress(string _baseApi) { defaultBaseAddress = _baseApi; } /// <summary> /// 设置测试地址,这个开发的时候可以用,优先级最高 /// </summary> /// <param name="_testBaseApi"></param> public void SetTestBaseAddress(string _testBaseApi) { testBaseAddress = _testBaseApi; } private async Task<string> GetToken() { TokenTools tokenTools = new TokenTools(); string token = await tokenTools.GetToken(); return token; } private string GetBaseAddress() { if (!string.IsNullOrWhiteSpace(testBaseAddress)) { // 本地education的测试地址: // baseAddress = "http://127.0.0.1:8804"; return testBaseAddress; } else { // 从配置文件中获取请求的基础地址 string baseAddress = SmartEDU.Utils.Appsettings.Configuration["ApiVisit:Address"]; if (string.IsNullOrWhiteSpace(baseAddress)) { baseAddress = defaultBaseAddress; } return baseAddress; } } /// <summary> /// 封装通用的get请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public async Task<ApiReturnData> GetAsync(string url) { ApiReturnData apiReturnData = new ApiReturnData(); string token = await GetToken(); if (string.IsNullOrWhiteSpace(token)) { apiReturnData.Msg = "token is empty"; apiReturnData.Code = -1; return apiReturnData; } string baseAddress = GetBaseAddress(); string questUrl = baseAddress + url; // 防止错误:One or more errors occurred. (The SSL connection could not be established, see inner exception.)” HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; }; clientHandler.SslProtocols = SslProtocols.None; HttpClient client = new HttpClient(clientHandler); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); string result = client.GetAsync(questUrl).Result.Content.ReadAsStringAsync().Result; if (string.IsNullOrWhiteSpace(result)) { apiReturnData.Msg = "请求失败!"; apiReturnData.Code = -1; return apiReturnData; } apiReturnData.Code = 200; apiReturnData.Msg = "请求成功!"; apiReturnData.Data = result; return apiReturnData; } /// <summary> /// 封装通用的Post请求 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public async Task<ApiReturnData> PostAsync(string url, object data) { ApiReturnData apiReturnData = new ApiReturnData(); string token = await GetToken(); if (string.IsNullOrWhiteSpace(token)) { apiReturnData.Msg = "token is empty"; apiReturnData.Code = -1; return apiReturnData; } string baseAddress = GetBaseAddress(); string questUrl = baseAddress + url; // 防止错误:One or more errors occurred. (The SSL connection could not be established, see inner exception.)” HttpClientHandler clientHandler = new HttpClientHandler(); clientHandler.ServerCertificateCustomValidationCallback += (sender, cert, chain, sslPolicyErrors) => { return true; }; clientHandler.SslProtocols = SslProtocols.None; HttpClient client = new HttpClient(clientHandler); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}"); StringContent strcontent = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); string result = client.PostAsync(questUrl, strcontent).Result.Content.ReadAsStringAsync().Result; if (string.IsNullOrWhiteSpace(result)) { apiReturnData.Msg = "请求失败!"; apiReturnData.Code = -1; return apiReturnData; } apiReturnData.Code = 200; apiReturnData.Msg = "请求成功!"; apiReturnData.Data = result; return apiReturnData; } } ``` ### 使用示例 #### 基础的get请求 ``` NewRequestTools newRequestTools = new NewRequestTools(); ApiReturnData apiResult = await newRequestTools.GetAsync("/labroom/api/MessageTask/GetTeacherTodayTeachingBad"); ``` #### 设置一点测试请求地址的 ``` #region 调用接口的基础东东 // 本地的测试地址: string testBaseAddress = "http://127.0.0.1:8805"; NewRequestTools newRequestTools = new NewRequestTools(); newRequestTools.SetTestBaseAddress(testBaseAddress); #endregion ApiReturnData apiResult = await newRequestTools.GetAsync("/labroom/api/MessageTask/GetTeacherTodayTeachingBad"); ``` #### post请求 ``` #region 调用接口的基础东东 // 测试环境的地址: string testBaseAddress = "https://smartedu-testapi.xx.com"; NewRequestTools requestTools = new NewRequestTools(); requestTools.SetTestBaseAddress(testBaseAddress); #endregion List<ClassCourseStIdDto> evalEndCourseList = endCourseInfoDto.data; ApiReturnData evalResultApi = await requestTools.PostAsync("/evaluation/api/Report/GetStudentCourseComplete", evalEndCourseList); ``` ### 其他备注 #### httpcent更多的用法参考 https://www.tnblog.net/aojiancc2/article/details/2707 #### HttpClient注入基础配置的用法参考 https://www.tnblog.net/notebook/article/details/8318 #### 关于错误One or more errors occurred. (The SSL connection could not be established, see inner exception.)的解决 https://www.tnblog.net/xiuxin3/article/details/8446