VideoConcat/Common/Tools/HttpUtils.cs
2025-01-27 22:07:25 +08:00

100 lines
2.8 KiB
C#

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<ApiResponse<T>> PostAsync<T>(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<T>.CreateAsync(response);
if (!apiResponse.IsSuccess)
{
LogUtils.Error($"PostAsync<{typeof(T)}> failed: {apiResponse.Code} {apiResponse.Msg}");
}
return apiResponse;
}
catch (TaskCanceledException)
{
return new ApiResponse<T>
{
IsSuccess = false,
Msg = "请求超时",
Code = 408
};
}
catch (Exception ex)
{
return new ApiResponse<T>
{
IsSuccess = false,
Msg = ex.Message,
Code = 500
};
}
}
}
public class ApiResponse<T>
{
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<ApiResponse<T>> CreateAsync(HttpResponseMessage response)
{
var result = new ApiResponse<T>
{
IsSuccess = response.IsSuccessStatusCode,
Code = (int)response.StatusCode,
RawContent = await response.Content.ReadAsStringAsync()
};
try
{
if (result.IsSuccess)
{
result.Data = JsonSerializer.Deserialize<T>(result.RawContent);
}
else
{
result.Msg = result.RawContent; // 或解析错误结构
}
}
catch (JsonException ex)
{
result.IsSuccess = false;
result.Msg = $"JSON解析失败: {ex.Message}";
}
return result;
}
}
}