我需要以编程方式通过POST发送表单。我有4个字段,一个复选框和一个提交按钮。我该怎么办呢?
答案 0 :(得分:2)
我使用这些函数假设您的问题是关于表单应用程序 你可以打电话
HttpPost(
post_url,
"field_name_1", value_1,
"field_name_2", value_2,
...);
他们是:
public static string HttpPost(string url, params object[] postData)
{
StringBuilder post = new StringBuilder();
for (int i = 0; i < postData.Length; i += 2)
post.Append(string.Format("{0}{1}={2}", i == 0 ? "" : "&", postData[i], postData[i + 1]));
return HttpPost(url, post.ToString());
}
public static string HttpPost(string url, string postData)
{
postData = postData.Replace("\r\n", "");
try
{
WebRequest req = WebRequest.Create(url);
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
return returnvalue;
}
catch (Exception ex)
{
Debug.WriteLine("POST Error on {0}\n {1}", url, ex.Message);
return "";
}
}
答案 1 :(得分:2)
这应该可以解决问题:
NameValueCollection formData = new NameValueCollection();
formData.Add("field1", "value1");
formData.Add("field2", "value2");
// ... and so on ...
WebClient client = new WebClient();
byte[] result = client.UploadValues("http://www.example.com", formData);
您没有传输复选框或提交按钮的信息。它总是名称和值。
答案 2 :(得分:0)
JQuery $ .Post()正是如此。