C# Web 请求与 POST 编码问题

问题描述 投票:0回答:2

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
的意思吗?

c# utf-8 urlencode
2个回答
12
投票

示例代码具有误导性,因为 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 所期望的。


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

© www.soinside.com 2019 - 2024. All rights reserved.