NetHelper.cs 3.22 KB
using HHECS.BllModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HHECS.Infrastructure.CommonHelper
{
    /// <summary>
    /// 与网络相关帮助类,比如socket、http等
    /// </summary>
    public class NetHelper
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static List<string> GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                return IpEntry.AddressList.Where(t => t.AddressFamily == AddressFamily.InterNetwork).Select(t => t.ToString()).ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }


        /// <summary>
        /// post提交json数据
        /// </summary>
        /// <typeparam name="T">泛型为返回值类型</typeparam>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <param name="timeout">约定的超时时间,单位秒,默认5秒</param>
        /// <returns>返回元组,第一项为结果,结果ok的情况下需要判断T的业务是否正常,第二项为耗时,当业务为异常时,耗时为0,单位毫秒,第三项为请求json,第四项为响应json,响应失败时无响应json</returns>
        public static async Task<(BllResult<T> result, long time, string request, string response)> PostJson<T>(string url, Object obj, int timeout = 5)
        {
            string postJsonString = JsonConvert.SerializeObject(obj);
            try
            {
                StringContent content = new StringContent(postJsonString, Encoding.UTF8, "application/json");
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(timeout));
                Stopwatch stopwatch = Stopwatch.StartNew();
                HttpResponseMessage response = await _httpClient.PostAsync(url, content, cancellationTokenSource.Token).ConfigureAwait(false);
                stopwatch.Stop();
                long m = stopwatch.ElapsedMilliseconds;
                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                    return (BllResultFactory.Success(JsonConvert.DeserializeObject<T>(responseBody)), m, postJsonString, responseBody);
                }
                else
                {
                    return (BllResultFactory.Error<T>($"请求上游系统失败:{response.ReasonPhrase}", "Net_E0002"), m, postJsonString, "");
                }

            }
            catch (Exception ex)
            {
                return (BllResultFactory.Create<T>(BllResultCode.Exception, default, $"请求上游系统失败:{ex.Message}-{ex.InnerException?.Message}", "Net_E0003"), 0, postJsonString, "");
            }
        }

    }
}