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 @ 2023-04-12 11:48  12不懂3  阅读(29)  评论(0编辑  收藏  举报
创作不易,请勿抄袭,欢迎转载!