.Net Standard HttpClient封裝Htt請求經常使用操做整理

1、經常使用Http操做html

1.Get請求,有參數,無參數web

2.Post 請求,有參數,無參數app

3.文件簡單下載async

修改NetHelper中Post請求方法Bug:請求編碼默認UTF8,字符串內存流讀取後這是到開始位置post

        /// <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();
            }
        }

 

之前代碼:ui

    /// <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 類庫的建立和使用url

.Net Standard Http請求實例spa

.Net Standard簡介指針

相關文章
相關標籤/搜索