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?

3

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.