71 lines
2.2 KiB
C#
71 lines
2.2 KiB
C#
![]() |
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace YD_WeChatApplet.Commons.Utils
|
|||
|
{
|
|||
|
public class HttpManager
|
|||
|
{
|
|||
|
public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
|
|||
|
{
|
|||
|
using (var client = new HttpClient())
|
|||
|
{
|
|||
|
client.Timeout = TimeSpan.FromSeconds(timeOut);
|
|||
|
|
|||
|
if (headers != null)
|
|||
|
{
|
|||
|
foreach (var header in headers)
|
|||
|
{
|
|||
|
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
HttpContent content = null;
|
|||
|
if (!string.IsNullOrEmpty(postData))
|
|||
|
{
|
|||
|
content = new StringContent(postData, Encoding.UTF8, contentType);
|
|||
|
}
|
|||
|
|
|||
|
try
|
|||
|
{
|
|||
|
var response = await client.PostAsync(url, content);
|
|||
|
response.EnsureSuccessStatusCode();
|
|||
|
return await response.Content.ReadAsStringAsync();
|
|||
|
}
|
|||
|
catch (Exception ex)
|
|||
|
{
|
|||
|
return ex.Message;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null)
|
|||
|
{
|
|||
|
using (var client = new HttpClient())
|
|||
|
{
|
|||
|
if (headers != null)
|
|||
|
{
|
|||
|
foreach (var header in headers)
|
|||
|
{
|
|||
|
client.DefaultRequestHeaders.Add(header.Key, header.Value);
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
try
|
|||
|
{
|
|||
|
var response = await client.GetAsync(url);
|
|||
|
|
|||
|
response.EnsureSuccessStatusCode();
|
|||
|
|
|||
|
return await response.Content.ReadAsStringAsync();
|
|||
|
}
|
|||
|
catch (Exception ex)
|
|||
|
{
|
|||
|
return ex.Message;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|