简体   繁体   English

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

[英]C# web request with POST encoding question

On the MSDN site there is an example of some C# code that shows how to make a web request with POST'ed data. 在MSDN站点上有一些C#代码示例,它显示了如何使用POST数据发出Web请求。 Here is an excerpt of that code: 以下是该代码的摘录:

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...

The line marked (*) is the line that puzzles me. 标有(*)的行是困扰我的那一行。 Shouldn't the data be encoded using the UrlEncode method rather than UTF8? 不应该使用UrlEncode方法而不是UTF8对数据进行编码吗? Isn't that what application/x-www-form-urlencoded implies? 这不是application/x-www-form-urlencoded意味着什么?

The sample code is misleading, because ContentType is set to application/x-www-form-urlencoded but the actual content is plain text. 示例代码具有误导性,因为ContentType设置为application / x-www-form-urlencoded,但实际内容是纯文本。 application/x-www-form-urlencoded is a string like this: application / x-www-form-urlencoded是这样的字符串:

name1=value1&name2=value2

The UrlEncode function is used to escape especial characters like '&' and '=' so a parser doesn't consider them as syntax. UrlEncode函数用于转义特殊字符,如'&'和'=',因此解析器不会将它们视为语法。 It takes a string (media type text/plain) and returns a string (media type application/x-www-form-urlencoded). 它需要一个字符串(媒体类型text / plain)并返回一个字符串(媒体类型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. Encoding.UTF8.GetBytes用于将字符串(媒体类型application / x-www-form-urlencoded在我们的例子中)转换为字节数组,这是WebRequest API所期望的。

As Max Toro indicated, the examples on the MSDN site are incorrect: a correct form POST requires the data to be URL encoded; 正如Max Toro指出的那样,MSDN网站上的示例是不正确的:正确的表单POST要求数据进行URL编码; 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. 由于MSDN示例中的数据不包含任何可通过编码更改的字符,因此它们在某种意义上已经编码。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM