HttpHelper

Rest

using ZKHK.Common.HttpRestSharp;
using ZKHK.Common.Model;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Bgy.Common.Extensions;

namespace ZKHK.Common.Helpers
{
    /// <summary>
    /// 基于 RestSharp 封装HttpHelper
    /// </summary>
    public class HttpHelper
    {

        #region Post请求
        public static async Task<RestApiResponse<T>> PostAsync<T>(string url) =>
            await RestPostAsync<T>(url, parameters: null, headers: null);

        public static async Task<RestApiResponse<T>> PostAsync<T>(string url, object parameters) =>
            await RestPostAsync<T>(url, parameters: parameters, headers: null);
        public static async Task<RestApiResponse<T>> PostAsync<T>(string url, object parameters, Dictionary<string, string> headers) =>
            await RestPostAsync<T>(url, parameters: parameters, headers: headers);


        #region Get请求

        public static async Task<RestApiResponse<T>> GetAsync<T>(string url) =>
            await RestGetAsync<T>(url, parameters: null, headers: null);
        public static async Task<RestApiResponse<T>> GetAsync<T>(string url, Dictionary<string, object> parameters) =>
            await RestGetAsync<T>(url, parameters, headers: null);
        public static async Task<RestApiResponse<T>> GetAsync<T>(string url, Dictionary<string, object> parameters, Dictionary<string, string> headers) =>
            await RestGetAsync<T>(url, parameters, headers: headers);
        #endregion

        #region 请求实现体

        /// <summary>
        /// GET请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        private static async Task<RestApiResponse<T>> RestGetAsync<T>(string url, Dictionary<string, object> parameters, Dictionary<string, string> headers = null)
        {
            var client = new RestClient($"{url}");
            var request = new RestRequest();
            if (headers != null && headers.Count > 0)
            {
                request.AddHeaders(headers);
            }
            if (parameters != null)
            {
                parameters.ToList().ForEach(item => request.AddParameter(item.Key, item.Value));
            }
            var response = await client.ExecuteGetAsync<T>(request);
            return await ResultMessageAsync<T>(response);
        }

        /// <summary>
        /// POST请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        private static async Task<RestApiResponse<T>> RestPostAsync<T>(string url, object parameters, Dictionary<string, string> headers = null)
        {
            var client = new RestClient($"{url}");
            var request = new RestRequest();
            if (headers != null && headers.Count > 0)
            {
                request.AddHeaders(headers);
            }
            if (parameters != null)
            {
                request.AddJsonBody(parameters); // 可以使用JsonSerializer
            }
            var response = await client.ExecutePostAsync<T>(request);
            return await ResultMessageAsync<T>(response);
        }
        #endregion

        private static Task<RestApiResponse<T>> ResultMessageAsync<T>(IRestResponse response)
        {
            var result = new RestApiResponse<T>
            {
                StatusCode = response.StatusCode,
                Request = response.Request,
                IsSuccessful = response.IsSuccessful
            };
            if (response.StatusCode != HttpStatusCode.OK)
            {
                result.ErrorMessage = response.ErrorMessage;
                result.ErrorException = response.ErrorException;
            }
            else
            {
                try
                {
                    result.Content = (T)Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content, typeof(T));
                }
                catch (Newtonsoft.Json.JsonException ex)
                {
                    result.ErrorMessage = ex.Message;
                    result.ErrorException = ex;
                    result = null;
                }

                result.RawBytes = response.RawBytes;
                result.ResponseUri = response.ResponseUri;
                result.Server = response.Server;
                result.StatusDescription = response.StatusDescription;
                result.ContentEncoding = response.ContentEncoding;
                result.ContentType = response.ContentType;
                result.ContentLength = response.ContentLength;
                result.ResponseStatus = response.ResponseStatus;
                result.ProtocolVersion = response.ProtocolVersion;
            }
            return Task.FromResult(result);
        }
        #endregion
    }
}

public class RestApiResponse<T>
{
    /// <summary>
    /// 请求是否成功
    /// </summary>
    public bool IsSuccessful { get; set; }
    /// <summary>
    /// 响应状态
    /// </summary>
    public HttpStatusCode StatusCode { get; set; }
    /// <summary>
    /// 错误信息
    /// </summary>
    public string ErrorMessage { get; set; }
    /// <summary>
    /// 响应内容的字符串表示
    /// </summary>
    public T Content { get; set; }
    /// <summary>
    /// 响应内容的字节数组
    /// </summary>
    public byte[] RawBytes { get; set; }
    /// <summary>
    /// 响应内容的字节长度
    /// </summary>
    public long ContentLength { get; set; }
    /// <summary>
    /// 响应内容类型
    /// </summary>
    public string ContentType { get; set; }
    /// <summary>
    /// 响应内容的编码
    /// </summary>
    public string ContentEncoding { get; set; }
    /// <summary>
    /// 实际响应内容的URL(如果重定向,则与请求不同)
    /// </summary>
    public Uri ResponseUri { get; set; }
    /// <summary>
    /// 主要用于ResponseStatus不正常时的调试
    /// </summary>
    public IRestRequest Request { get; set; }
    /// <summary>
    /// 返回的HTTP状态说明
    /// </summary>
    public string StatusDescription { get; set; }
    /// <summary>
    /// HttpWebResponse.服务器
    /// </summary>
    public string Server { get; set; }
    /// <summary>
    /// 请求的状态。将为传输错误返回错误。HTTP错误将仍然返回已完成响应状态,改为检查状态代码
    /// </summary>
    public ResponseStatus ResponseStatus { get; set; }
    /// <summary>
    /// 请求期间引发的异常(如果有)
    /// </summary>
    public Exception ErrorException { get; set; }
    /// <summary>
    /// HTTP协议版本(1.0、1.1等)
    /// </summary>
    public Version ProtocolVersion { get; set; }
    /// <summary>
    /// 服务器随响应返回的Cookie
    /// </summary>
    [Obsolete]
    public IList<RestResponseCookie> Cookies { get; set; }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值