2025-09-04 18:28:02 +08:00

269 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SWS.Commons;
using SWS.Model;
namespace SWS.Service
{
public class HttpService
{
public HttpService()
{
}
public void Init(string address, int port)
{
// 如果 GlobalObject.client 已经是 null初始化一个新的 HttpClient 实例
//if (GlobalObject.client == null)
//{
GlobalObject.client = new HttpClient()
{
BaseAddress = new Uri($"http://{address}:{port}/api/"),
Timeout = TimeSpan.FromSeconds(120)
};
//}
//else
//{
// // 如果已经有 client 实例,则更新它的 BaseAddress
// GlobalObject.client.BaseAddress = new Uri($"http://{address}:{port}/api/");
//}
}
/// <summary>
/// 带入授权码。
/// </summary>
/// <param name="httpClient"></param>
protected virtual void OnInitAuthorizationCode()
{
//httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows 10.0.22621.1265; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/110.0.835.163 Safari/535.1");
//if (AuthorizationCode.IsNullOrEmpty() || httpClient == null) return;
//httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthorizationCode);
}
protected virtual void OnInitRequestHeader(HttpClient httpClient, string mediaType)
{
//httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(mediaType));
httpClient.DefaultRequestHeaders.Add("Accept", mediaType);
httpClient.DefaultRequestHeaders.Add("ContentType", mediaType);
}
private void WriteLog(string requestUri, string strJson)
{
try
{
var uri = new Uri(GlobalObject.client.BaseAddress + requestUri);
var funName = uri.Segments.Last();
LoggerHelper.Current.WriteJson(funName, strJson);
}
catch { }
}
public async Task<learunHttpRes<T>> GetAsync<T>(string requestUri)
{
//httpClient.Timeout = TimeSpan.FromSeconds(3000);
OnInitAuthorizationCode();
string result = string.Empty;
learunHttpRes<T> resultObj = null;
try
{
if (!GlobalObject.client.DefaultRequestHeaders.Any()&& GlobalObject.userInfo!=null)
{
GlobalObject.client.DefaultRequestHeaders.Add("logintoken", GlobalObject.userInfo.token);
GlobalObject.client.DefaultRequestHeaders.Add("loginkey", GlobalObject.userInfo.loginMark);
}
var response = await GlobalObject.client.GetAsync(requestUri);
if (response.StatusCode != HttpStatusCode.OK)
{
string errorMsg = $"服务器地址 [{requestUri}] 获取数据失败, 返回HTTP代码" + response.StatusCode;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
result = await response.Content.ReadAsStringAsync();
WriteLog(requestUri, result);
resultObj = JsonConvert.DeserializeObject<learunHttpRes<T>>(result);
}
catch (JsonException)
{
string errorMsg = $"服务器地址 [{requestUri}] 解析为{typeof(T).Name}失败,原始返回数据为: " + result;
LoggerHelper.Current.Error(errorMsg);
resultObj = new learunHttpRes<T>() { code = -100, info = errorMsg };
return resultObj;
}
catch (Exception ex)
{
string errorMsg = $"接口:{requestUri}失败,异常:{ex.Message} ";
LoggerHelper.Current.Error(errorMsg);
resultObj = new learunHttpRes<T>() { code = -100, info=errorMsg };
return resultObj;
}
if (resultObj.code != 200)
{
switch (resultObj.code)
{
case 400:
case 500:
break;
//业务错误不是http本质错误
default:
string errorMsg = $"服务器地址 [{requestUri}] Get失败, 返回自定义代码:" + resultObj.code;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
}
LoggerHelper.Current.Info($"Get成功{requestUri}");
return resultObj;
}
public async Task<T> GetAsyncByOnlyData<T>(string requestUri)
{
//httpClient.Timeout = TimeSpan.FromSeconds(3000);
OnInitAuthorizationCode();
string result = string.Empty;
T resultObj;
try
{
var response = await GlobalObject.client.GetAsync(requestUri);
if (response.StatusCode != HttpStatusCode.OK)
{
string errorMsg = $"服务器地址 [{requestUri}] 获取数据失败, 返回HTTP代码" + response.StatusCode;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
result = await response.Content.ReadAsStringAsync();
WriteLog(requestUri, result);
resultObj = JsonConvert.DeserializeObject<T>(result);
}
catch (JsonException)
{
string errorMsg = $"服务器地址 [{requestUri}] 解析为{typeof(T).Name}失败,原始返回数据为: " + result;
LoggerHelper.Current.Error(errorMsg);
throw new JsonException(errorMsg);
}
catch (Exception ex)
{
string errorMsg = $"接口:{requestUri}失败,异常:{ex.Message} ";
LoggerHelper.Current.Error(errorMsg);
throw new JsonException(errorMsg);
}
LoggerHelper.Current.Info($"Get成功{requestUri}");
return resultObj;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T">响应后的返回数据的类型</typeparam>
/// <typeparam name="T1">POST数据对象的类型</typeparam>
/// <param name="requestUri"></param>
/// <param name="entity"></param>
/// <returns></returns>
/// <exception cref="HttpRequestException"></exception>
/// <exception cref="JsonException"></exception>
public async Task<learunHttpRes<T>> PostBodyAsync<T, T1>(string requestUri, T1 postObj)
{
OnInitAuthorizationCode();
string contentType = "application/json";
string strContent = postObj != null ? JsonConvert.SerializeObject(postObj) : "";
var content = new StringContent(strContent, Encoding.UTF8, contentType);
OnInitRequestHeader(GlobalObject.client, contentType);
learunHttpRes<T> resultObj = null;
string result = string.Empty;
try
{
var response = await GlobalObject.client.PostAsync(requestUri, content);
if (response.StatusCode != HttpStatusCode.OK)
{
string errorMsg = $"服务器地址 [{requestUri}] Post数据失败, 返回HTTP代码" + response.StatusCode;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
result = await response.Content.ReadAsStringAsync();
WriteLog(requestUri, result);
resultObj = JsonConvert.DeserializeObject<learunHttpRes<T>>(result);
}
catch (JsonException)
{
string errorMsg = $"服务器地址 [{requestUri}] 解析为{typeof(T).Name}失败,原始返回数据为: " + result;
LoggerHelper.Current.Error(errorMsg);
resultObj = new learunHttpRes<T>() { code = -100, info = errorMsg };
return resultObj;
}
catch (Exception ex)
{
string errorMsg = $"接口:{requestUri}失败,参数数据为:{strContent},异常:{ex.Message} ";
LoggerHelper.Current.Error(errorMsg);
resultObj = new learunHttpRes<T>() { code = -100, info = errorMsg };
return resultObj;
}
if (resultObj.code != 200)
{
switch (resultObj.code)
{
case 400:
case 500:
break;
//业务错误不是http本质错误
default:
string errorMsg = $"服务器地址 [{requestUri}] Post失败, 返回自定义代码:" + resultObj.code;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
}
LoggerHelper.Current.Info($"Post成功{requestUri}");
return resultObj;
}
public async Task<T> PostFileAsync<T>(string requestUri, Stream stream, string fileName)
{
OnInitAuthorizationCode();
string contentType = "multipart/form-data";
var streamContent = new StreamContent(stream, (int)stream.Length);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
var content = new MultipartFormDataContent
{
{ streamContent, "file", fileName }
};
OnInitRequestHeader(GlobalObject.client, contentType);
var response = await GlobalObject.client.PostAsync(requestUri, content);
if (response.StatusCode != HttpStatusCode.OK)
{
string errorMsg = $"服务器地址 [{requestUri}] Post数据失败, 返回HTTP代码" + response.StatusCode;
LoggerHelper.Current.Error(errorMsg);
throw new HttpRequestException(errorMsg);
}
var result = await response.Content.ReadAsStringAsync();
T resultObj;
try
{
resultObj = JsonConvert.DeserializeObject<T>(result);
}
catch (JsonException)
{
string errorMsg = $"服务器地址 [{requestUri}] 解析为 string 失败,原始返回数据为: " + result;
LoggerHelper.Current.Error(errorMsg);
throw new JsonException(errorMsg);
}
LoggerHelper.Current.Info($"Post上传文件成功{requestUri}");
return resultObj;
}
}
}