c#_ HttpClient_ application/x-www-form-urlencoded_ Parameter escape

Time:2022-2-26

Guide: only use httpclient library to simulate HTTP request and post request header

Content type: application / x-www-form-urlencoded # problem of escaping when non alphanumeric characters are encountered
Code:https://github.com/dswyzx/forblogs
And result screenshot

 

1: Problem: due to the docking interface, the character “+” exists in the parameters, resulting in differences between the two sides when confirming the parameters
Specifically, the “+” character encapsulates httprequestmessage in the httpclient request body Content, all parameters are packed into byte array by default, and the parameters are not encoded in advance as the default operation of the browser
“Data is encoded in'&'Separated key value pairs with'='Separator keys and valuesCharacters other than letters or numbers will bepercent-encoding“Invoking:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods/POST
2: Initiate request:
 

HttpUtility.UrlEncode(string str)

Use the URLEncode method to escape characters in the body of the request body in advance For example, “+” is escaped as “% 2B”, and “” is escaped as “+” or “% 20”https://developer.mozilla.org/zh-CN/docs/Glossary/percent-encoding

Then it is spliced into a string to provide the content parameter required by stringcontent

3: Receive parameters

This experiment uses Net framework 4.5 the MVC framework generated by default simulates accepting form request parameters

Curl is attached for reference only

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

 

4: Concluding remarks

I move bricks all day, but I don’t understand each other’s Dharma Take this record for reference