在使用.Net时,我们有时会对一些外部连接中的数据进行处理,那么封装一个请求的方法就很有必要了
封装HttpHelper
内置了两种方法,Post和/Get
csharp
/// <summary>
/// 创建POST方式的HTTP请求--form-data
/// </summary>
/// <param name="url"></param>
/// <param name="dic"></param>
/// <returns></returns>
public static string PostJsonData(string url, Dictionary<string, string> dic, Dictionary<string, string> headers = null)
{
string str = "";
try
{
HttpClient client = new HttpClient();
var postContent = new MultipartFormDataContent();
string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
// 添加额外的头部信息
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
foreach (var key in dic.Keys)
{
postContent.Add(new StringContent(dic[key].ToString()), key);
}
HttpResponseMessage response = client.PostAsync(url, postContent).Result;
str = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
return ("PostJsonData:" + ex.ToString());
}
return str;
}
/// <summary>
/// 创建Get方式的HTTP请求--form-data
/// </summary>
/// <param name="url"></param>
/// <param name="dic"></param>
/// <returns></returns>
public static string GetJsonData(string url, Dictionary<string, string> parameters = null, Dictionary<string, string> headers = null)
{
string str = "";
try
{
HttpClient client = new HttpClient();
// 添加额外的头部信息
if (headers != null)
{
foreach (var header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
// 构建查询参数
if (parameters != null)
{
var queryBuilder = new StringBuilder("?");
foreach (var param in parameters)
{
queryBuilder.Append($"{param.Key}={Uri.EscapeDataString(param.Value)}&");
}
url += queryBuilder.ToString().TrimEnd('&');
}
HttpResponseMessage response = client.GetAsync(url).Result;
str = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
return ("GetJsonData:" + ex.ToString());
}
return str;
}
使用
在使用时,我们只需要传递请求地址和参数,表头可以不传
csharp
public AssetsQueryConfig GetAssetsQueryList(GzParam List)
{
//请求地址
string url = "111111111111111"+ "/asset/getAssetsQueryList";
//数据
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("OrgNum", List.OrgNum);
param.Add("SiteNum", List.SiteNum);
param.Add("AssetNum", List.AssetNum);
param.Add("SerialNum", List.SerialNum);
//表头
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("authorization", dict.ToString());
string responseJson = HttpHelper.GetJsonData(url, param, headers);
//解析获取的值
dynamic responseObject = JsonConvert.DeserializeObject(responseJson);
}