|
|
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;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
}
|