using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace QYZH.InteractiveMagazine.Common.Helpers
{
///
/// HTTP请求工具类
///
public static class HttpHelper
{
private static readonly HttpClient _httpClient = new HttpClient();
///
/// 设置默认请求头
///
static HttpHelper()
{
_httpClient.Timeout = TimeSpan.FromSeconds(30);
}
///
/// 发送GET请求
///
/// 请求地址
/// 响应内容字符串
public static async Task GetAsync(string url)
{
HttpResponseMessage response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
///
/// 发送GET请求并反序列化为指定类型
///
/// 响应类型
/// 请求地址
/// 反序列化后的对象
public static async Task GetAsync(string url)
{
string json = await GetAsync(url);
return JsonConvert.DeserializeObject(json);
}
///
/// 发送POST请求
///
/// 请求地址
/// 请求数据
/// 响应内容字符串
public static async Task PostAsync(string url, object data)
{
string json = JsonConvert.SerializeObject(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
///
/// 发送POST请求并反序列化为指定类型
///
/// 响应类型
/// 请求地址
/// 请求数据
/// 反序列化后的对象
public static async Task PostAsync(string url, object data)
{
string json = await PostAsync(url, data);
return JsonConvert.DeserializeObject(json);
}
///
/// 发送DELETE请求
///
/// 请求地址
/// 响应内容字符串
public static async Task DeleteAsync(string url)
{
HttpResponseMessage response = await _httpClient.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
///
/// 发送PUT请求
///
/// 请求地址
/// 请求数据
/// 响应内容字符串
public static async Task PutAsync(string url, object data)
{
string json = JsonConvert.SerializeObject(data);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PutAsync(url, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}