.Net Standard HttpClient封裝Htt請求常用操作整理

林堯彬發表於2020-04-04

一、常用Http操作

1.Get請求,有引數,無引數

2.Post 請求,有引數,無引數

3.檔案簡單下載

修改NetHelper中Post請求方法Bug:請求編碼預設UTF8,字串記憶體流讀取後這是到開始位置

        /// <summary>
        /// Post 請求,無參(注:預設使用UTF8編碼)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> PostAsync(string url, string content = "")
        {
            HttpClient client = new HttpClient();
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(content);
                ms.Write(bytes, 0, bytes.Length);
                ms.Seek(0, SeekOrigin.Begin);//設定指標讀取位置,否則傳送無效
                HttpContent hc = new StreamContent(ms);
                HttpResponseMessage resp = await client.PostAsync(url, hc);
                return await resp.Content.ReadAsStringAsync();
            }
        }

 

以前程式碼:

    /// <summary>
    /// http協議請求方法封裝
    /// </summary>
    public class NetHelper
    {
        #region Get請求
        /// <summary>
        /// get請求,無參
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> GetAsync(string url)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage resp = await client.GetAsync(url);
            //獲取響應狀態
            //respMsg.StatusCode==200請求成功
            //獲取請求內容
            HttpContent respContent = resp.Content;
            return await respContent.ReadAsStringAsync();
        }
        /// <summary>
        /// Get 請求,指定引數
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static async Task<string> GetAsync(string url, Dictionary<string, string> dic)
        {
            //引數處理
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dic.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            return await GetAsync(builder.ToString());
        }

        /// <summary>
        /// get 請求 -同步處理
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Get(string url)
        {
            Task<string> result = GetAsync(url);
            result.Wait();
            return result.Result;
        }
        /// <summary>
        /// Get請求-同步處理
        /// </summary>
        /// <param name="url">請求地址</param>
        /// <param name="dic">請求引數</param>
        /// <returns></returns>
        public static string Get(string url, Dictionary<string, string> dic)
        {
            //引數處理
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dic.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }
            return Get(builder.ToString());
        }
        #endregion

        #region Post 請求處理
        /// <summary>
        /// Post 請求,無參
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<string> PostAsync(string url, string content = "")
        {
            HttpClient client = new HttpClient();
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] bytes = Encoding.Unicode.GetBytes(content);
                ms.Write(bytes, 0, bytes.Length);
                HttpContent hc = new StreamContent(ms);
                HttpResponseMessage resp = await client.PostAsync(url, null);
                return await resp.Content.ReadAsStringAsync();
            }
        }
        /// <summary>
        /// Post 請求,處理引數
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static async Task<string> PostAsync(string url, Dictionary<string, string> dic)
        {
            HttpClient client = new HttpClient();
            FormUrlEncodedContent data = new FormUrlEncodedContent(dic);
            var r = await client.PostAsync(url, data);
            return await r.Content.ReadAsStringAsync();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xhtml+xml"));
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml", 0.9));
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/webp"));
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
            //hc.Headers.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
            //hc.Headers.Add("Timeout", timeOut.ToString());
            //hc.Headers.Add("KeepAlive", "true");
        }

        /// <summary>
        /// Post請求,同步,無參
        /// </summary>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string Post(string url, string content = "")
        {
            Task<string> str = PostAsync(url, content);
            str.Wait();
            return str.Result;
        }
        /// <summary>
        /// Post 請求,同步,引數處理
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string Post(string url, Dictionary<string, string> dic)
        {
            Task<string> str = PostAsync(url, dic);
            str.Wait();
            return str.Result;
        }
        #endregion

        #region 下載檔案處理
        /// <summary>
        /// 下載檔案
        /// </summary>
        /// <param name="url">連結地址</param>
        /// <param name="target">儲存地址</param>
        /// <returns></returns>
        public static bool DownLoad(string url, string target)
        {
            try
            {
                HttpClient client = new HttpClient();
                var t = client.GetByteArrayAsync(url);
                t.Wait();

                var bytes = t.Result;
                using (FileStream fs = new FileStream(target, FileMode.Create))
                {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception("下載檔案失敗,", ex);
            }
        }
        #endregion
    }

 

 

更多:

.Net Standard 類庫的建立和使用

.Net Standard Http請求例項

.Net Standard簡介

轉載於:https://www.cnblogs.com/tianma3798/p/9025172.html

相關文章