HttpHelper

复制代码
public class HttpHelpe
{
    public static async Task<T> GetAsync<T>(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
    {
        return await RequestAsync<T>(url, "GET", postData, contentType, timeOut, headers);
    }

    public static async Task<T> PostAsync<T>(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
    {
        return await RequestAsync<T>(url, "POST", postData, contentType, timeOut, headers);
    }

    public static async Task<T> PutAsync<T>(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
    {
        return await RequestAsync<T>(url, "PUT", postData, contentType, timeOut, headers);
    }

    public static async Task<T> DeleteAsync<T>(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary<string, string> headers = null)
    {
        return await RequestAsync<T>(url, "DELETE", postData, contentType, timeOut, headers);
    }

    private static async Task<T> RequestAsync<T>(string url, string method, string postData = null, string contentType = null, int timeOut = 30,
        Dictionary<string, string> headers = null)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = method;
        request.Timeout = timeOut * 1000;

        if (!string.IsNullOrEmpty(contentType))
        {
            request.ContentType = contentType;
        }

        if (headers != null)
        {
            foreach (var header in headers)
            {
                request.Headers[header.Key] = header.Value;
            }
        }

        if (!string.IsNullOrEmpty(postData) && (method == "POST" || method == "PUT"))
        {
            byte[] dataBytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = dataBytes.Length;

            using (Stream stream = await request.GetRequestStreamAsync())
            {
                await stream.WriteAsync(dataBytes, 0, dataBytes.Length);
            }
        }

        using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(stream);
                string responseBody = await reader.ReadToEndAsync();
                T responseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseBody);
                return responseObject;
            }
        }
    }
}
复制代码

 

posted @   12不懂3  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
历史上的今天:
2022-04-12 理解:TPS,QPS,吞吐量
2018-04-12 c# 快捷键
创作不易,请勿抄袭,欢迎转载!
点击右上角即可分享
微信分享提示