using LogLibrary.Log;
|
using Newtonsoft.Json;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace WIDESEA_Common;
|
|
public class HttpsClient
|
{
|
private static readonly LogFactory LogFactory = new LogFactory();
|
|
// 封装一个用HttpClient发送GET请求的方法有参数
|
public static async Task<string> GetAsync(string url, Dictionary<string, string> parameters)
|
{
|
// 记录请求参数
|
LogRequestParameters(parameters);
|
|
// 将参数拼接到URL中
|
string queryString = string.Join("&", parameters.Select(x => $"{x.Key}={x.Value}"));
|
url += "?" + queryString;
|
|
// 创建HttpClient实例
|
using (HttpClient client = new HttpClient())
|
{
|
// 发送GET请求并获取响应
|
HttpResponseMessage response = await client.GetAsync(url);
|
|
// 确保响应成功
|
response.EnsureSuccessStatusCode();
|
|
// 读取响应内容
|
string responseBody = await response.Content.ReadAsStringAsync();
|
|
// 记录响应参数
|
LogResponseParameters(responseBody);
|
|
// 返回响应内容
|
return responseBody;
|
}
|
}
|
|
// 封装一个用HttpClient发送Post请求的方法有参数
|
public static async Task<string> PostAsync(string url, Dictionary<string, string> parameters)
|
{
|
// 记录请求参数
|
LogRequestParameters(parameters);
|
|
// 创建HttpClient实例
|
using (HttpClient client = new HttpClient())
|
{
|
// 将参数转换为FormUrlEncodedContent
|
FormUrlEncodedContent content = new FormUrlEncodedContent(parameters);
|
|
// 发送POST请求并获取响应
|
HttpResponseMessage response = await client.PostAsync(url, content);
|
|
// 确保响应成功
|
response.EnsureSuccessStatusCode();
|
|
// 读取响应内容
|
string responseBody = await response.Content.ReadAsStringAsync();
|
|
// 记录响应参数
|
LogResponseParameters(responseBody);
|
|
// 返回响应内容
|
return responseBody;
|
}
|
}
|
|
private static void LogRequestParameters(Dictionary<string, string> parameters)
|
{
|
LogFactory.GetLog("API接口").Info(true, "请求参数: " + JsonConvert.SerializeObject(parameters));
|
}
|
|
private static void LogResponseParameters(string responseBody)
|
{
|
LogFactory.GetLog("API接口").Info(true, "响应参数: " + responseBody);
|
}
|
}
|