c#_HttpClient_application/x-www-form-urlencoded

導讀: 僅供使用httpclient庫模擬http請求,Post請求頭git

Content-Type: application/x-www-form-urlencoded 遇到 非字母或數字的字符 時轉義的問題
直接上code: https://github.com/dswyzx/forblogs
及結果截圖

 

1:問題:因對接接口,參數內存在字符"+",致使雙方對參數進行確認時發生分歧
具體表現爲:"+"字符在httpclient 爲HttpRequestMessage 請求體封裝HttpRequestMessage.Content時,所有參數默認被打包爲byte數組,並無像瀏覽器默認操做同樣事先對參數進行encoding操做
"數據被編碼成以  '&' 分隔的鍵-值對, 同時以  '=' 分隔鍵和值 . 非字母或數字的字符會被  percent-encoding" 援引: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST
2:發起請求:
 
HttpUtility.UrlEncode(string str)

 使用 urlencode方法,對請求體的body內存在須要轉義字符時提早進行轉義.好比"+"轉義爲"%2b"," "轉義爲"+"或"%20" 援引  https://developer.mozilla.org/zh-CN/docs/Glossary/percent-encodinggithub

而後再拼接爲字符串以提供給StringContent所需的content參數.數組

3:接收參數瀏覽器

本實驗使用.NET Framework 4.5 默認生成的MVC框架模擬接受Form請求參數.app

另附curl僅供參考框架

curl --location --request POST 'https://localhost:44343/home/GetUserInfo' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'k=1%2b1'

 

4:結束語curl

整日搬磚,卻對方法體不求甚解.藉此記錄,以供參考編碼

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息