最近在寫項目,這里打算整理出項目中比較常用的功能。
通常我們發送http請求是在前端使用表單或者ajax,那么.net core后台發送http請求該如何呢?
這里我使用HttpClient
因為通常提交的方法是post或者get,我使用簡單工廠模式來設計此功能。
using System; using System.Collections.Generic; using System.Text; namespace Tools.HttpClientHelper { public abstract class AbsHttpHelper { //請求的主機 public string baseAddr = string.Empty; //是否啟用驗證 public bool isAuth = false; //驗證字符串 public string auth = string.Empty;//"Bearer "+token //請求路徑 public string path = string.Empty; public abstract string GetResult(); } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Tools.HttpClientHelper { public class GetHelper: AbsHttpHelper { /// <summary> /// /// </summary> /// <param name="baseAddr">訪問的主機</param> /// <param name="auth">驗證字符串</param> /// <param name="path">請求的路徑</param> public GetHelper(string baseAddr, string auth, string path) { this.baseAddr = baseAddr; this.auth = auth; this.path = path; } public override string GetResult() { string resultContent = string.Empty; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(baseAddr); var t = client.GetAsync(path); t.Wait(); var result = t.Result; resultContent = result.Content.ReadAsStringAsync().Result; } return resultContent; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Tools.HttpClientHelper { public class PostHelper:AbsHttpHelper { //發送的數據 private FormUrlEncodedContent content = null; /// <summary> /// 構造方法 /// </summary> /// <param name="baseAddr">請求的主機</param> /// <param name="auth">驗證字符串</param> /// <param name="path">請求路徑</param> /// <param name="isAuth">是否啟用驗證</param> /// <param name="content">發送的數據</param> public PostHelper(string baseAddr, string auth, string path, bool isAuth, FormUrlEncodedContent content) { this.baseAddr = baseAddr; this.auth = auth; this.content = content; this.path = path; this.isAuth = isAuth; } public override string GetResult() { string resultContent = string.Empty; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(baseAddr); if (isAuth) { client.DefaultRequestHeaders.Add("Authorization", auth); } var t = client.PostAsync(path, content); t.Wait(); var result = t.Result; resultContent = result.Content.ReadAsStringAsync().Result; } return resultContent; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; namespace Tools.HttpClientHelper { /// <summary> /// 創建http請求對象的工廠類 /// </summary> public class HttpFactory { /// <summary> /// 創建http請求對象 /// </summary> /// <param name="method">get/post</param> /// <param name="baseAddr">請求的主機</param> /// <param name="auth">驗證字符串</param> /// <param name="path">請求路徑</param> /// <param name="isAuth">是否啟用驗證,get請求時為false</param> /// <param name="content">發送的數據,get請求時為null</param> /// <returns></returns> public AbsHttpHelper CreateHttpHelper(string method, string baseAddr, string auth, string path, bool isAuth, FormUrlEncodedContent content) { AbsHttpHelper helper = null; method = method.ToLower(); switch (method) { case "get": helper = new GetHelper(baseAddr, auth, path); break; case "post": helper = new PostHelper(baseAddr, auth, path, isAuth, content); break; } return helper; } } }
調用:
HttpFactory httpFactory = new HttpFactory(); AbsHttpHelper helper = httpFactory.CreateHttpHelper("get", baseAddr, "", path, false, null); string rs = helper.GetResult();
注意,這里的post方法只支持表單的鍵值對提交,content 如下
var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("apiCode", "GetUser"), new KeyValuePair<string, string>("pCount", "10"), new KeyValuePair<string, string>("pNum", "1") });
如果要傳json,則需使用StringContent,如下:
protected async Task SendMsgAsync(string touser, string msg) { string sendMsgPath = AppConfig.CreateConfig().sendMsgPath + AccessTokenJob.token; //發送的路徑 var msgObj = new { content = msg }; var content = new { touser = touser, msgtype = "text", AppConfig.CreateConfig().agentid, text = msgObj, safe = 0 }; var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(content); StringContent contentStr = new StringContent(jsonStr); using (HttpClient client = new HttpClient()) { var respMsg = await client.PostAsync(sendMsgPath, contentStr); string msgBody = await respMsg.Content.ReadAsStringAsync(); } }