You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
3.0 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Estsh.Core.Util
{
public class HttpClientHelper
{
/// <summary>
/// 通过Get请求数据
/// </summary>
/// <returns></returns>
public static async Task<string> HttpGetMathod(string url)
{
using (HttpClient httpClient = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(3000)
})
{
var response = await httpClient.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
/// <summary>
/// 通过Get请求数据
/// </summary>
/// <returns></returns>
public static async Task<string> HttpGetMathod(string url, Dictionary<string, string> param)
{
using (HttpClient httpClient = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(3000)
})
{
StringBuilder buffer = new StringBuilder("?");
int i = 0;
foreach (string key in param.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, param[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, param[key]);
}
i++;
}
var response = await httpClient.GetAsync(url + buffer.ToString());
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
/// <summary>
/// 使用Post请求数据application/json
/// </summary>
/// <returns></returns>
public static string HttpPostByJsonMathod(string url, object model)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
var response = httpClient.PostAsync(
url,
new StringContent(
Newtonsoft.Json.JsonConvert.SerializeObject(model),
Encoding.UTF8,
"application/json")).GetAwaiter().GetResult();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
else
{
return string.Empty;
}
}
}
catch (System.Exception ex)
{
LogHelper.Error("调用API接口错误" + url, ex);
return string.Empty;
}
}
}
}