代码之家  ›  专栏  ›  技术社区  ›  rlandster

C带后编码问题的Web请求

  •  9
  • rlandster  · 技术社区  · 15 年前

    在msdn站点上有一个 example of some C# code 这显示了如何使用发布的数据进行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 暗示?

    2 回复  |  直到 15 年前
        1
  •  11
  •   Max Toro    15 年前

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

    name1=value1&name2=value2
    

    urlencode函数用于转义特殊字符,如“&”和“=”,因此解析器不会将它们视为语法。它接受一个字符串(media type text/plain)并返回一个字符串(media type application/x-www-form-urlencoded)。

    encoding.utf8.getbytes用于将字符串(在我们的例子中是media type application/x-www-form-urlencoded)转换为字节数组,这正是webrequest api所期望的。

        2
  •  9
  •   rlandster    15 年前

    正如Max Toro所指出的,msdn站点上的示例不正确:正确的表单发布要求对数据进行URL编码;由于msdn示例中的数据不包含任何将通过编码更改的字符,因此在某种意义上,它们已经编码。

    正确的代码将具有 System.Web.HttpUtility.UrlEncode 在将每个名称/值对组合到 name1=value1&name2=value2 字符串。

    此页面非常有用: http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx