Reputation: 831
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?
Upvotes: 1
Views: 3507
Reputation: 101682
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.
Upvotes: 0
Reputation: 35353
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);
Upvotes: 3