1

So I want to post to a form within the same domain entirely from code. I think I have everything I need except how to include the form data. The values I need to include are from hidden fields and input fields, let's call them:

<input type="text" name="login" id="login"/>
<input type="password" name="p" id="p"/>
<input type = hidden name="a" id="a"/>

What I have so far is

WebRequest req = WebRequest.Create("http://www.blah.com/form.aspx")
req.ContentType = "application/x-www-form-urlencoded"
req.Method = "POST"

How do I include the values for those three input fields in the request?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user609926
  • 801
  • 2
  • 12
  • 25
  • One of the answers to this question: http://stackoverflow.com/questions/2962155/c-sharp-web-request-with-post-encoding-question suggests having a look at this page: http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx which I think is precisely what you need. The most relevant part is the `EncodeAndAddItem()` method at the end of the code and how that method is used. – JLRishe Jan 12 '13 at 19:22
  • possible duplicate of [.net post form in code behind](http://stackoverflow.com/questions/11394229/net-post-form-in-code-behind) – David Basarab Jan 14 '13 at 15:29
  • 1
    I think my situation is slightly different than that one. I don't want to rebuild the form in code just post the form values. – user609926 Jan 17 '13 at 00:05

2 Answers2

3
NameValueCollection nv = new NameValueCollection();
nv.Add("login", "xxx");
nv.Add("p", "yyy");
nv.Add("a", "zzz");

WebClient wc = new WebClient();
byte[] ret = wc.UploadValues(""http://www.blah.com/form.aspx", nv);
I4V
  • 34,891
  • 6
  • 67
  • 79
0

As shown in the link provided in my comment above, if you are using a WebRequest and not a WebClient, probably the thing to do is build up a string of key-value pairs separated by &, with the values url encoded:

  foreach(KeyValuePair<string, string> pair in items)
  {      
    StringBuilder postData = new StringBuilder();
    if (postData .Length!=0)
    {
       postData .Append("&");
    }
    postData .Append(pair.Key);
    postData .Append("=");
    postData .Append(System.Web.HttpUtility.UrlEncode(pair.Value));
  }

And when you send the request, use this string to set the ContentLength and send it to the RequestStream:

request.ContentLength = postData.Length;
using(Stream writeStream = request.GetRequestStream())
{
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] bytes = encoding.GetBytes(postData);
    writeStream.Write(bytes, 0, bytes.Length);
}

You may be able to distill the functionality for your needs so it doesn't need to be split out into so many methods.

JLRishe
  • 99,490
  • 19
  • 131
  • 169