gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:35:27 30 4
gpt4 key购买 nike

在 MSDN 站点上有一个 example of some C# code这显示了如何使用 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 函数用于转义特殊字符,如“&”和“=”,因此解析器不会将它们视为语法。它接受一个字符串(媒体类型文本/纯文本)并返回一个字符串(媒体类型应用程序/x-www-form-urlencoded)。

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

关于带有 POST 编码问题的 C# Web 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2962155/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com