开发者

C# : How do i post a form to a website with some checked checkboxes?

开发者 https://www.devze.com 2022-12-13 13:33 出处:网络
I\'m working in C#, and I want to POST to a website that has multiple checkboxes and returns a datafile depending on which 开发者_如何学Pythoncheckboxes are checked.

I'm working in C#, and I want to POST to a website that has multiple checkboxes and returns a datafile depending on which 开发者_如何学Pythoncheckboxes are checked.

First of all, how do I post a form with checked checkboxes ? And once that is done, how do I get the datafile the site sends me ?


With this simple ASP code, we can see how checkboxes values are sent through a POST request:

tst.asp

<%
Dim chks
chks = Request.Form("chks")
%>
<html>
<head>
    <title>Test page</title>
</head>
<body>
    <form name="someForm" action="" method="POST">
        <input type="checkbox" id="chk01" name="chks" value="v1" />
        <input type="checkbox" id="chk02" name="chks" value="v2" />
        <input type="checkbox" id="chk03" name="chks" value="v3" />
        <input type="submit" value="Submit!" />
    </form>
    <h3>Last "chks" = <%= chks %></h3>
</body>
</html>

The H3 line show us this, if we check all the checkboxes:

Last "chks" = v1, v2, v3

Now we know how the data should be posted. With the sample code below, you should be able to do it.

C# method sample

using System.Text;
using System.Net;
using System.IO;
using System;

...

void DoIt()
{
    String querystring = "chks=v1, v2, v3";
    byte[] buffer = Encoding.UTF8.GetBytes(querystring);

    WebRequest webrequest = HttpWebRequest.Create("http://someUrl/tst.asp");
    webrequest.ContentType = "application/x-www-form-urlencoded";
    webrequest.Method = "POST";
    webrequest.ContentLength = buffer.Length;

    using (Stream data = webrequest.GetRequestStream())
    {
        data.Write(buffer, 0, buffer.Length);
    }

    using (HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse())
    {
        if (webresponse.StatusCode == HttpStatusCode.OK)
        {
            /* post ok */
        }
    }
}

Hope I've helped.

Useful links:

  • Reference: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
  • Example: http://www.netomatix.com/httppostdata.aspx
  • Example: http://msdn.microsoft.com/en-us/debx8sh9.aspx


You'll want to make some WebRequests using the System.Net.HttpWebRequest namespace.

You can create a GET or a POST connection with HttpWebRequest.

There's a great article on it here and you can also check out System.Net.HttpWebRequest on MSDN.

0

精彩评论

暂无评论...
验证码 换一张
取 消