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

rla*_*ter 9 c# urlencode utf-8

在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...
Run Code Online (Sandbox Code Playgroud)

标记(*)的线是令我困惑的线.不应该使用UrlEncode方法而不是UTF8对数据进行编码吗?这不是什么application/x-www-form-urlencoded暗示?

Max*_*oro 11

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

name1=value1&name2=value2
Run Code Online (Sandbox Code Playgroud)

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

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


rla*_*ter 9

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

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

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