Reputation: 3511
<form action="https://somewebsiteaddrest" method="post">
<input name="Var1" type="hidden" value="Variable 1 value" />
<input name="Var2" type="hidden" value="Variable 2 value" />
<input name="Var3" type="hidden" value="Variable 3 value" />
<input name="Var4" type="hidden" value="Variable 4 value" />
<input name="Var5" type="hidden" value="Variable 6 value" />
<input type="submit" value="Go now" />
</form>
I want to create equal post method and redirection (in C#) without using this form and javascript frm.submit()
;
I've a C# code snippet which I expect to do the stuff.
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
string postData = "What to write here? here should be variable i guess.";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
string postData
what to write in postData to get the same effect as it will be by using form
and form.submit()
? Thanks in advance
Upvotes: 1
Views: 2652
Reputation: 8141
POST requests provide a body that uses URL encoding to send the data.
You can use this method to encode your data.
So for example you can have code like this:
string ToQueryString(IEnumerable data)
{
return string.Join("&", data.Select(d => HttpUtility.UrlEncode(d.ToString())));
}
Upvotes: 0
Reputation: 700322
The post data should be URL-encoded form data, i.e. key=value pairs separated by &
characters. Use the UrlEncode
method to encode the values:
string postData =
"Var1=" + HttpUtility.UrlEncode("Variable 1 value")+
"&Var2=" + HttpUtility.UrlEncode("Variable 2 value")+
"&Var3=" + HttpUtility.UrlEncode("Variable 3 value")+
"&Var4=" + HttpUtility.UrlEncode("Variable 4 value")+
"&Var5=" + HttpUtility.UrlEncode("Variable 6 value");
Upvotes: 1