C#请求Post接口
生活随笔
收集整理的這篇文章主要介紹了
C#请求Post接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 應用場景
- 2. 解決方案
- 3. 問題匯總
- 3.1 傳參問題
- 3.2 設置代理
- 4. 參考鏈接
1. 應用場景
防止前端直接調用某些隱私接口造成數據泄露,可以采用后端調用接口的方式,這樣避免前端傳參導致的數據泄露問題。
2. 解決方案
使用類HttpWebRequest,核心代碼如下:
/// <summary> /// 接口請求 /// </summary> /// <param name="url">請求地址</param> /// <returns></returns> public static string GetToken(string url){string result = "";//返回結果HttpWebRequest request = null;HttpWebResponse response = null;Stream reqStream = null;try{request = (HttpWebRequest)WebRequest.Create(url);request.Method = "POST";request.ReadWriteTimeout = 5000;//System.Net.WebProxy wp = new System.Net.WebProxy("127.0.0.1:5555", true);// 調試模式下,用于postman攔截測試參數問題//request.Proxy = wp;request.ProtocolVersion = HttpVersion.Version10;request.KeepAlive = false;request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";request.ServicePoint.Expect100Continue = false;//添加Authorization到HTTP頭request.Headers.Add("Authorization", "Basic ****************");Dictionary<string, string> parameters = new Dictionary<string, string>(); //參數列表parameters.Add("paraName", "paraValue");byte[] data = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8")); //使用utf-8格式組裝post參數request.ContentLength = data.Length;reqStream = request.GetRequestStream();reqStream.Write(data, 0, data.Length);reqStream.Close();//獲取服務端返回response = (HttpWebResponse)request.GetResponse();StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);result = sr.ReadToEnd().Trim();sr.Close();}catch (Exception e){LogManager.DefaultLogger.Error(e);}finally{//關閉連接和流if (response != null){response.Close();}if (request != null){request.Abort();}}return result;}//組裝請求參數 private string BuildQuery(IDictionary<string, string> parameters, string encode) {StringBuilder postData = new StringBuilder();bool hasParam = false;IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();while (dem.MoveNext()){string name = dem.Current.Key;string value = dem.Current.Value;// 忽略參數名或參數值為空的參數if (!string.IsNullOrEmpty(name)){if (hasParam){postData.Append("&");}postData.Append(name);postData.Append("=");if (encode == "gb2312"){postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));}else if (encode == "utf8"){postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));}else{postData.Append(value);}hasParam = true;}}return postData.ToString(); }3. 問題匯總
3.1 傳參問題
接口請求時總是無法返回正確結果,使用同樣的參數在Postman中返回結果正常,通過[設置代理](#3.2 設置代理)進行請求攔截,發現應該時參數傳遞時出現問題,應該進行encode。參數處理參考如下代碼:
Dictionary<string, string> parameters = new Dictionary<string, string>(); //參數列表 parameters.Add("paraName", "paraValue"); byte[] data = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8")); //使用utf-8格式組裝 request.ContentLength = data.Length; reqStream = request.GetRequestStream(); reqStream.Write(data, 0, data.Length); reqStream.Close(); //獲取服務端返回 response = (HttpWebResponse)request.GetResponse();//組裝請求參數 private string BuildQuery(IDictionary<string, string> parameters, string encode) {StringBuilder postData = new StringBuilder();bool hasParam = false;IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();while (dem.MoveNext()){string name = dem.Current.Key;string value = dem.Current.Value;// 忽略參數名或參數值為空的參數if (!string.IsNullOrEmpty(name)){if (hasParam){postData.Append("&");}postData.Append(name);postData.Append("=");if (encode == "gb2312"){postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));}else if (encode == "utf8"){postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));}else{postData.Append(value);}hasParam = true;}}return postData.ToString(); }3.2 設置代理
當我們想要查看接口請求的詳細內容時,包括請求頭與參數等,可以配合Postman設置代理,進行接口請求攔截。共兩個步驟:
在代碼中添加如下:
System.Net.WebProxy wp = new System.Net.WebProxy("127.0.0.1:5555", true);// 調試模式下,用于postman攔截測試參數問題 request.Proxy = wp;Postman代理端口默認是5555
Postman開啟代理
注意:調試模式下Postman才可以攔截到請求
4. 參考鏈接
- C# WebRequest設置代理訪問
- C# HttpWebRequest post 請求傳參數
總結
以上是生活随笔為你收集整理的C#请求Post接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 接口请求时params与data的区别
- 下一篇: C#中EventLog的使用