C# HttpClient 的那些坑
阿新 • • 發佈:2021-09-17
點選檢視程式碼
/// /// HttpPost /// /// 非【application/json】 建議使用 Method HttpPost 使用此方法可能會字元超長導致請求400 /// /// /// /// /// /// public static string HttpClientPost(string url, string requestJson, Dictionary headers = null,string contentType= "application/json") { try { string result = string.Empty; Uri postUrl = new Uri(url); using (var httpClient = new HttpClient()) { if (headers != null) { foreach (var header in headers) httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } using (HttpContent httpContent = new StringContent(requestJson)) { if (headers != null) { foreach (var header in headers) httpContent.Headers.Add(header.Key, header.Value); } httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); httpClient.Timeout = new TimeSpan(0, 0, 60); result = httpClient.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result; } } return result; } catch (Exception e) { throw e; } }
呼叫方式:
// model 為json物件
HttpClientPost("url",JsonConvert.SerializeObject(model))
當使用【ContentType】為【application/json】的時候,上述方法一點問題沒有,引數長度也沒有限制,然而使用【application/x-www-form-urlencoded】或使用【form-data】時,引數有了限制,長度和get請求的限制一致,而使用此方法請求,依然可以收到返回值,只不過返回值為空,響應丟擲【400-bad request】的錯誤程式碼,就很迷惑。。。 然後調整成下列方法後,問題就其妙的解決了。
點選檢視程式碼
/// /// 發起POST同步請求(Key Value) /// Method【application/json】【application/x-www-form-urlencoded】 /// 引數超長時使用此方法 /// /// /// /// /// public static string HttpPost(string baseAddr, string path, FormUrlEncodedContent content,Dictionary header=null, string contentType ="") { try { string resultContent = string.Empty; using (HttpClient client = new HttpClient()) { // client.BaseAddress = new Uri(baseAddr); // header if (header != null) foreach (var item in header) { content.Headers.Add(item.Key, item.Value); } if (!string.IsNullOrEmpty(contentType)) { content.Headers.ContentType = new MediaTypeHeaderValue(contentType); } HttpResponseMessage response = client.PostAsync(baseAddr+path, content).Result; resultContent = response.Content.ReadAsStringAsync().Result; } return resultContent; } catch (Exception) { throw; } }
使用方式:
點選檢視程式碼
var content = new FormUrlEncodedContent(new[] {
// body 為請求介面的引數名稱,依據個人實際需求調整;引數依然為json物件
new KeyValuePair("body", JsonConvert.SerializeObject(model))
});
HttpPost("url", "可移除", content, _header, "application/x-www-form-urlencoded")
這個時候,介面就可以使用了,並且上面這個方法可以在型別(contentType)中使用,不會出現引數超長及其他問題,唯一美中不足的是,引數格式化這塊沒有第一個方法簡單。
這個問題困擾了一天的時間,特此記錄下,表示我現在忐忑的心情。。
本文來自部落格園,作者:ThinkWsir,轉載請註明原文連結:https://www.cnblogs.com/thinkw/p/15304712.html