带有POST编码问题的C#web请求

在MSDN网站上有一些C#代码的示例,它显示了如何使用POST数据发出Web请求。 以下是该代码的摘录:

WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx "); request.Method = "POST"; string postData = "This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes (postData); // (*) request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream (); dataStream.Write (byteArray, 0, byteArray.Length); dataStream.Close (); WebResponse response = request.GetResponse (); ...more... 

标有(*)的行是困扰我的行。 不应该使用UrlEncode方法而不是UTF8对数据进行编码吗? 这不是application/x-www-form-urlencoded意味着什么?

示例代码具有误导性,因为ContentType设置为application / x-www-form-urlencoded,但实际内容是纯文本。 application / x-www-form-urlencoded是这样的字符串:

 name1=value1&name2=value2 

UrlEncode函数用于转义特殊字符,如’&’和’=’,因此解析器不会将它们视为语法。 它需要一个字符串(媒体类型text / plain)并返回一个字符串(媒体类型application / x-www-form-urlencoded)。

Encoding.UTF8.GetBytes用于将字符串(在我们的例子中为媒体类型application / x-www-form-urlencoded)转换为字节数组,这是WebRequest API所期望的。

正如Max Toro指出的那样,MSDN网站上的示例是不正确的:正确的表单POST要求数据进行URL编码; 由于MSDN示例中的数据不包含任何可通过编码更改的字符,因此它们在某种意义上已经编码。

正确的代码将对每个名称/值对的名称和值进行System.Web.HttpUtility.UrlEncode调用,然后将它们组合到name1=value1&name2=value2字符串中。

这个页面很有帮助: http : //geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx