C# web request with POST encoding question

前端 未结 2 1844
孤街浪徒
孤街浪徒 2020-12-16 20:25

On the MSDN site there is an example of some C# code that shows how to make a web request with POST\'ed data. Here is an excerpt of that code:

WebRequest req         


        
相关标签:
2条回答
  • 2020-12-16 21:09

    The sample code is misleading, because ContentType is set to application/x-www-form-urlencoded but the actual content is plain text. application/x-www-form-urlencoded is a string like this:

    name1=value1&name2=value2
    

    The UrlEncode function is used to escape especial characters like '&' and '=' so a parser doesn't consider them as syntax. It takes a string (media type text/plain) and returns a string (media type application/x-www-form-urlencoded).

    Encoding.UTF8.GetBytes is used to convert the string (media type application/x-www-form-urlencoded in our case) into an array of bytes, which is what the WebRequest API expects.

    0 讨论(0)
  • 2020-12-16 21:22

    As Max Toro indicated, the examples on the MSDN site are incorrect: a correct form POST requires the data to be URL encoded; since the data in the MSDN example does not contain any characters that would be changed by encoding, they are, in a sense, already encoded.

    The correct code would have a System.Web.HttpUtility.UrlEncode call on the names and values of each name/value pair before combining them into the name1=value1&name2=value2 string.

    This page was helpful: http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx

    0 讨论(0)
提交回复
热议问题