HttpService.cs 2.11 KB
using HHECS.BllModel;
using HHECS.RobotTool.Dto.WeldMonitor;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;

namespace HHECS.RobotTool.Service
{
    public class HttpService
    {
        private readonly HttpClient _httpClient;

        private readonly JsonSerializerOptions jsonSerializeOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            PropertyNameCaseInsensitive = true
        };

        private readonly JsonSerializerOptions jsonDeserializeOptions = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };

        public HttpService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public BllResult SetWeldMonitorData(WeldMonitorDto monitorDto)
        {
            try
            {
                var json = JsonSerializer.Serialize(monitorDto, jsonSerializeOptions);
                var content = new StringContent(json);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var result = _httpClient.PostAsync("http://172.16.29.87:6002/api/setData", content).Result;
                var resultContent = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                if (result.IsSuccessStatusCode)
                {
                    var sendResult = JsonSerializer.Deserialize<WeldMonitorResult>(resultContent, jsonDeserializeOptions);
                    if (sendResult?.Status == true)
                    {
                        return BllResultFactory.Success();
                    }
                    return BllResultFactory.Error($"发送失败:{sendResult?.Message}");
                }

                if (string.IsNullOrEmpty(resultContent))
                {
                    resultContent = result.ReasonPhrase;
                }
                return BllResultFactory.Error($"推送失败:{resultContent}");
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }
    }
}