用POST编程地发送表单

本文关键字:表单 POST 编程 | 更新日期: 2023-09-27 18:11:14

我需要通过POST以编程方式发送表单。我有4个字段,一个复选框和提交按钮。我该怎么做呢?

用POST编程地发送表单

假设您的问题是关于表单应用程序,我使用这些函数。
你可以调用

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 "";
    }
}

这应该能奏效:

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);

信息,你有复选框或提交按钮没有被转移。名字总是价值

JQuery $. post()就是这样做的。