John said:
has anyone successfully used HttpWebRequest or WebClient class to
simulate submission of a simple HTML form?
for example: a very simple plain-vanilla form with a textbox and a
button. when the button is clicked the form is submitted with the
textbox contents.
could you please post some sample code? thanks.
That's a full blown WebRequest/WebResponse sample including URL encoding.
public void PostForm(string url, string formData, string encodingName) {
// URL encode the post data, applying the character encoding given by
// encodingName.
MemoryStream content = new MemoryStream(formData.Length * 2);
Encoding encoding = Encoding.GetEncoding(encodingName);
string[] keyValuePairs = formData.Split('&', '=');
int numberOfPairs = keyValuePairs.Length;
bool isKey = true;
foreach (string keyValue in keyValuePairs) {
byte[] bytes = HttpUtility.UrlEncodeToBytes(keyValue, encoding);
content.Write(bytes, 0, bytes.Length);
if (isKey) {
content.WriteByte((byte) '=');
}
else {
content.WriteByte((byte) '&');
}
isKey = !isKey;
}
// We'll end up with one surplus '&' -- shouldn't hurt, but we cut it
anyway
content.SetLength(content.Length - 1);
// That's the actual HTTP part of the sample
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "POST";
request.ContentType = String.Format(
"application/x-www-form-urlencoded; charset={0}", encodingName);
request.ContentLength = content.Length;
using (Stream requestStream = request.GetRequestStream()) {
content.WriteTo(requestStream);
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
using (Stream responseStream = response.GetResponseStream()) {
byte[] buffer = new byte[response.ContentLength];
responseStream.Read(buffer, 0, buffer.Length);
// Process buffer... e.g. write to file, decode to string, etc.
}
}
Cheers,