<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>
我想创建相同的post方法和重定向(在C#中)而不使用此表单和 javascript frm.submit()
;
我有一个C#代码片段,我希望能够做到。
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
在postData中写什么来获得与使用form
和form.submit()
相同的效果?提前致谢
答案 0 :(得分:1)
帖子数据应该是URL编码的表格数据,即由&
个字符分隔的键=值对。使用UrlEncode
method对值进行编码:
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");
答案 1 :(得分:0)
POSTDATA = “VAR1 = XXX&安培; VAR2 = YYYY ....”
答案 2 :(得分:0)
POST requests提供使用URL编码发送数据的正文。
您可以使用this method对数据进行编码。
例如,您可以使用以下代码:
string ToQueryString(IEnumerable data)
{
return string.Join("&", data.Select(d => HttpUtility.UrlEncode(d.ToString())));
}