C# HttpClientHelper

 public class HttpClientHelper
    {

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponse(string url, out string statusCode)
        {
            if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }


            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                using (HttpResponseMessage response = httpClient.GetAsync(url).Result)
                {
                    statusCode = response.StatusCode.ToString();
                    if (response.IsSuccessStatusCode)
                    {
                        string result = response.Content.ReadAsStringAsync().Result;
                        return result;
                    }
                    return null;
                }
            }
        }
        public static string RestfulGet(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            // Get response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());
                // Console application output
                return reader.ReadToEnd();
            }
        }
        public static T GetResponse<T>(string url)where T : class, new()
        {
            if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }
            using (var httpClient = new HttpClient()) 
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                using (HttpResponseMessage response = httpClient.GetAsync(url).Result) 
                {
                    T result = default(T);
                    if (response.IsSuccessStatusCode)
                    {
                        Task<string> t = response.Content.ReadAsStringAsync();
                        string s = t.Result;
                        result = JsonConvert.DeserializeObject<T>(s);
                    }
                    return result;
                }
            }
        }
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponse(string url)
        {
            if (url.StartsWith("https"))
            { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }

            using (HttpClient httpClient = new HttpClient())
            {
                using (HttpResponseMessage response = httpClient.GetAsync(url).Result)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string result = response.Content.ReadAsStringAsync().Result;
                        return result;
                    }
                    return null;
                }
            }
        }


        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData">post数据</param>
        /// <returns></returns>
        public static string PostResponse(string url, string postData, out string statusCode)
        {
            if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }
            using (HttpContent httpContent = new StringContent(postData)) 
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                using (HttpClient httpClient = new HttpClient())
                {
                    using (HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result)
                    {
                        statusCode = response.StatusCode.ToString();
                        if (response.IsSuccessStatusCode)
                        {
                            string result = response.Content.ReadAsStringAsync().Result;
                            return result;
                        }
                        return null;
                    }
                }
            }
        }

        /// <summary>
        /// 发起post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">url</param>
        /// <param name="postData">post数据</param>
        /// <returns></returns>
        public static T PostResponse<T>(string url, string postData)where T : class, new()
        {
            if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }
            using (HttpContent httpContent = new StringContent(postData)) 
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                using (HttpClient httpClient = new HttpClient())
                {
                    T result = default(T);
                    using (HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            Task<string> t = response.Content.ReadAsStringAsync();
                            string s = t.Result;

                            result = JsonConvert.DeserializeObject<T>(s);
                        }
                        return result;
                    }
                }
            } 
        }




        public static string PostResponse(string url, string postData, string token, string appId, string serviceURL, out string statusCode)
        {
            if (url.StartsWith("https")) { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }


            using (HttpContent httpContent = new StringContent(postData))
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                httpContent.Headers.Add("token", token);
                httpContent.Headers.Add("appId", appId);
                httpContent.Headers.Add("serviceURL", serviceURL);
                using (HttpClient httpClient = new HttpClient())
                {
                    using (HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result)
                    {
                        statusCode = response.StatusCode.ToString();
                        if (response.IsSuccessStatusCode)
                        {
                            string result = response.Content.ReadAsStringAsync().Result;
                            return result;
                        }
                        return null;
                    }
                }
            }
        }

        /// <summary>
        /// 修改请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PatchResponse(string url, string postData)
        {

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Method = "PATCH";

            byte[] btBodys = Encoding.UTF8.GetBytes(postData);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) 
            {
                using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    string responseContent = streamReader.ReadToEnd();
                    httpWebResponse.Close();
                    streamReader.Close();
                    httpWebRequest.Abort();
                    httpWebResponse.Close();
                    return responseContent;
                }
            }
        }

        /// <summary>
        /// 创建Form表单API请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string CreateFormResponse(string url, string postData)
        {
            if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }

            using (HttpContent httpContent = new StringContent(postData)) 
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
                using (HttpClient httpClient = new HttpClient())
                {
                    using (HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            string result = response.Content.ReadAsStringAsync().Result;
                            return result;
                        }
                        return null;
                    }
                }
            }
                
        }

        /// <summary>
        /// 删除API请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool DeleteResponse(string url)
        {
            if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }
            using (HttpClient httpClient = new HttpClient()) 
            {
                using (HttpResponseMessage response = httpClient.DeleteAsync(url).Result)
                {
                    return response.IsSuccessStatusCode;
                }
            }   
        }

        /// <summary>
        /// 修改或者更改API    
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PutResponse(string url, string postData)
        {
            if (url.StartsWith("https")) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; }


            using (HttpContent httpContent = new StringContent(postData)) 
            {
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") { CharSet = "utf-8" };
                using (HttpClient httpClient = new HttpClient())
                {
                    using (HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result)
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            string result = response.Content.ReadAsStringAsync().Result;
                            return result;
                        }
                        return null;
                    }
                }
            }
        }

       



    }

 

posted @ 2021-12-27 12:32  LuoCore  阅读(621)  评论(0编辑  收藏  举报