81 lines
2.3 KiB
C#
81 lines
2.3 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace VideoConcat.Common.Tools
|
|
{
|
|
|
|
|
|
// HTTP 请求封装类
|
|
public class HttpHelper
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
|
|
public HttpHelper()
|
|
{
|
|
|
|
_httpClient = new HttpClient
|
|
{
|
|
BaseAddress = new Uri("https://admin.xiangbing.vip")
|
|
};
|
|
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
|
|
}
|
|
|
|
// 发送 GET 请求
|
|
public async Task<ApiResponse<T>> GetAsync<T>(string url)
|
|
{
|
|
try
|
|
{
|
|
var response = await _httpClient.GetAsync(url);
|
|
response.EnsureSuccessStatusCode();
|
|
var content = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<ApiResponse<T>>(content);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ApiResponse<T>
|
|
{
|
|
Code = 500,
|
|
Msg = $"请求出错: {ex.Message}",
|
|
Data = default
|
|
};
|
|
}
|
|
}
|
|
|
|
// 发送 POST 请求
|
|
public async Task<ApiResponse<T>> PostAsync<T>(string url, object data)
|
|
{
|
|
try
|
|
{
|
|
var json = JsonConvert.SerializeObject(data);
|
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
var response = await _httpClient.PostAsync(url, content);
|
|
response.EnsureSuccessStatusCode();
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
return JsonConvert.DeserializeObject<ApiResponse<T>>(responseContent);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ApiResponse<T>
|
|
{
|
|
Code = 500,
|
|
Msg = $"请求出错: {ex.Message}",
|
|
Data = default
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
public class ApiResponse<T>
|
|
{
|
|
public int Code { get; set; }
|
|
public T Data { get; set; }
|
|
public string Msg { get; set; }
|
|
}
|
|
}
|