【问题标题】:POST a form from a .NET Application从 .NET 应用程序发布表单
【发布时间】:2010-05-19 04:23:12
【问题描述】:

我不熟悉 http 的东西,但我如何能够向网站提交数据?我想从控制台应用程序“按下”一个提交按钮。这不是我自己的网站。

这是页面来源的一部分,不确定是否有任何相关性:

<form action="rate.php" method="post">

查看了 HttpWebRequest 类,但不熟悉需要填写哪些属性。

对不起,我含糊不清,但我对http不熟悉。

【问题讨论】:

标签: c# http post


【解决方案1】:

这是来自 MSDN 的 c/p。

    // Create a request using a URL that can receive a post. 
    WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx ");
    // Set the Method property of the request to POST.
    request.Method = "POST";
    // Create POST data and convert it to a byte array.
    string postData = "This is a test that posts this string to a Web server.";
    byte[] byteArray = Encoding.UTF8.GetBytes (postData);
    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.
    Stream dataStream = request.GetRequestStream ();
    // Write the data to the request stream.
    dataStream.Write (byteArray, 0, byteArray.Length);
    // Close the Stream object.
    dataStream.Close ();
    // Get the response.
    WebResponse response = request.GetResponse ();
    // Display the status.
    Console.WriteLine (((HttpWebResponse)response).StatusDescription);
    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream ();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader (dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd ();
    // Display the content.
    Console.WriteLine (responseFromServer);
    // Clean up the streams.
    reader.Close ();
    dataStream.Close ();
    response.Close ();

link to page

这个过程非常简单,但您需要首先弄清楚您需要发送什么以及任何其他可能需要的特殊编码/cookies/等。我建议您对 Firefox 使用 Fiddler 和/或 Firebug。您可以通过网页查看工作请求中发生的一切,然后您可以在应用中模仿相同的行为。

【讨论】:

  • -1 表示代码中没有 using 语句 - 无论它是否来自 MSDN。
  • @John:省略 using 语句是一种常见的做法。请保存您对真正误导性内容的反对意见。此答案的作者不应因试图提供帮助而受到惩罚。
  • @Wim:我不记得上次我做某事是因为你告诉我的。哦,等等:从来没有发生过。
  • @Wim:这是导致新开发人员泄漏资源的常见做法,以及不良异常处理的其他常见做法。我把我的反对票留给那些让剪切粘贴开发者从坏习惯开始的人。
  • @John,我同意 Wim,它确实引起了评论,但是不赞成投票是矫枉过正的恕我直言
【解决方案2】:

【讨论】:

    【解决方案3】:

    可以在此处找到一个灵活且易于使用的示例:C# File Upload with form fields, cookies and headers

    【讨论】:

      【解决方案4】:
      Response.Write("hello!");
      Response.End();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2012-10-16
        • 2020-04-08
        • 2017-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多