HTTP請求型別列舉
namespace Demo { /// <summary> /// HTTP請求型別 /// </summary> public enum HttpRequestType { /// <summary> /// GET請求 /// </summary> GET, /// <summary> /// POST請求 /// </summary> POST, /// <summary> /// PUT請求 /// </summary> PUT, /// <summary> /// DELETE請求 /// </summary> DELETE, } }
HTTP幫助類
using Newtonsoft.Json; using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Demo { /// <summary> /// HTTP幫助類 /// </summary> public static class HttpHelper { /// <summary> /// HTTP請求 /// </summary> /// <param name="url"></param> /// <param name="jwt"></param> /// <param name="requestType"></param> /// <param name="data"></param> /// <param name="encoding"></param> /// <param name="mediaType"></param> /// <returns></returns> /// <exception cref="CustomException"></exception> public static async Task<string> HttpRequestAsync(string url, string jwt = null, HttpRequestType? requestType = HttpRequestType.GET, string data = null, Encoding encoding = null, string mediaType = "application/json") { // 忽略SSL驗證 HttpClientHandler handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; // HTTP客戶端 using HttpClient client = new HttpClient(); // 設定JWT身份驗證頭 if (jwt != null) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); } // 構造請求內容 StringContent content = new StringContent(string.Empty); if (data != null) { content = new StringContent(JsonConvert.SerializeObject(data), encoding ??= Encoding.UTF8, mediaType); } // 發起請求 Logger.Info(String.Format("http request, url: {0}, type: {1}, body: {2}", url, requestType, data)); HttpResponseMessage response = null; // 判斷請求型別 switch (requestType) { case HttpRequestType.GET: response = await client.GetAsync(url); break; case HttpRequestType.POST: response = await client.PostAsync(url, content); break; case HttpRequestType.PUT: response = await client.PutAsync(url, content); break; case HttpRequestType.DELETE: response = await client.DeleteAsync(url); break; } // 檢查響應是否成功 if (response?.IsSuccessStatusCode == true) { // 讀取響應內容 string responseBody = await response.Content.ReadAsStringAsync(); Logger.Info(String.Format("http response, url: {0}, type: {1}, body: {2}", url, requestType, responseBody)); return responseBody; } else { throw new Exception(String.Format("HTTP請求失敗,狀態碼:{0}", response?.StatusCode)); } } /// <summary> /// HTTP請求 /// </summary> /// <param name="url"></param> /// <param name="jwt"></param> /// <param name="requestType"></param> /// <param name="data"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="Exception"></exception> public static async Task<string> HttpRequestAsync(string url, string jwt = null, HttpRequestType? requestType = HttpRequestType.GET, string data = null, CancellationToken cancellationToken = default) { try { // 忽略SSL驗證 HttpClientHandler handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; // HTTP客戶端 using HttpClient client = new HttpClient(handler); // 設定JWT身份驗證頭 if (!string.IsNullOrEmpty(jwt)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt); } // 構造請求內容 StringContent content = new StringContent(string.Empty); if (!string.IsNullOrEmpty(data)) { content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); } // 發起請求 Logger.Info(String.Format("http request, url: {0}, type: {1}, body: {2}", url, requestType, data)); HttpResponseMessage response = null; // 判斷請求型別 switch (requestType) { case HttpRequestType.GET: response = await client.GetAsync(url, cancellationToken); break; case HttpRequestType.POST: response = await client.PostAsync(url, content, cancellationToken); break; case HttpRequestType.PUT: response = await client.PutAsync(url, content, cancellationToken); break; case HttpRequestType.DELETE: response = await client.DeleteAsync(url, cancellationToken); break; } // 檢查響應是否成功 if (response?.IsSuccessStatusCode == true) { // 讀取響應內容 string responseBody = await response.Content.ReadAsStringAsync(); Logger.Info(String.Format("http response, url: {0}, type: {1}, body: {2}", url, requestType, responseBody)); return responseBody; } else { throw new Exception(String.Format("HTTP請求失敗,狀態碼:{0}", (int)response?.StatusCode)); } } catch (OperationCanceledException ex) { throw new Exception(String.Format("HTTP請求失敗,請求已終止:{0}", ex.Message)); } catch (Exception) { throw; } } } }