C# HTTP帮助类

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,
    }
}
View Code

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;
            }
        }
    }
}
View Code

 

posted @ 2024-04-02 09:41  Mr_Xul  阅读(37)  评论(0编辑  收藏  举报