HttpService.cs
2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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);
}
}
}
}