導讀: 僅供使用httpclient庫模擬http請求,Post請求頭
Content-Type: application/x-www-form-urlencoded 遇到 非字母或數字的字符 時轉義的問題 直接上code:https://github.com/dswyzx/forblogs及結果截圖
1:問題:因對接介面,引數記憶體在字符"+",導致雙方對引數進行確認時發生分歧 具體表現為:"+"字符在httpclient 為HttpRequestMessage 請求體封裝HttpRequestMessage.Content時,全部引數默認被打包為byte陣列,并沒有像瀏覽器默認操作一樣事先對引數進行encoding操作
"資料被編碼成以2:發起請求:'&'分隔的鍵-值對, 同時以'='分隔鍵和值. 非字母或數字的字符會被 percent-encoding" 援引:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST
HttpUtility.UrlEncode(string str)
使用 urlencode方法,對請求體的body記憶體在需要轉義字符時提前進行轉義.比如"+"轉義為"%2b"," "轉義為"+"或"%20" 援引 https://developer.mozilla.org/zh-CN/docs/Glossary/percent-encoding
然后再拼接為字串以提供給StringContent所需的content引數.
3:接收引數
本實驗使用.NET Framework 4.5 默認生成的MVC框架模擬接受Form請求引數.
另附curl僅供參考
curl --location --request POST 'https://localhost:44343/home/GetUserInfo' \ --header 'Content-Type: application/x-www-form-urlencoded' \ --data-urlencode 'k=1%2b1'
4:結束語
整日搬磚,卻對方法體不求甚解.借此記錄,以供參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/260835.html
標籤:C#
上一篇:【C#】反射的用法及效率對比
