using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace VideoConcat.Common.Tools { public class HttpService { private readonly HttpClient _httpClient; public HttpService() { _httpClient = new HttpClient { //BaseAddress = new Uri("https://admin.xiangbing.vip"), BaseAddress = new Uri("http://127.0.0.1:8080"), }; } public async Task> PostAsync(string url, object data) { try { var json = JsonSerializer.Serialize(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(url, content); var apiResponse = await ApiResponse.CreateAsync(response); if (!apiResponse.IsSuccess) { LogUtils.Error($"PostAsync<{typeof(T)}> failed: {apiResponse.Code} {apiResponse.Msg}"); } return apiResponse; } catch (TaskCanceledException) { return new ApiResponse { IsSuccess = false, Msg = "请求超时", Code = 408 }; } catch (Exception ex) { return new ApiResponse { IsSuccess = false, Msg = ex.Message, Code = 500 }; } } } public class ApiResponse { public bool IsSuccess { get; set; } public int Code { get; set; } public T Data { get; set; } public string Msg { get; set; } public string RawContent { get; set; } public static async Task> CreateAsync(HttpResponseMessage response) { var result = new ApiResponse { IsSuccess = response.IsSuccessStatusCode, Code = (int)response.StatusCode, RawContent = await response.Content.ReadAsStringAsync() }; try { if (result.IsSuccess) { result.Data = JsonSerializer.Deserialize(result.RawContent); } else { result.Msg = result.RawContent; // 或解析错误结构 } } catch (JsonException ex) { result.IsSuccess = false; result.Msg = $"JSON解析失败: {ex.Message}"; } return result; } } }