1. 程式人生 > >.Net Standard HttpClient封裝Htt請求常用操作整理

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

return AD eth ive ada encoding web ray lencod

一、常用Http操作

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

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

3.文件簡單下載

    /// <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簡介

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