开发者

programatically send a form with POST

开发者 https://www.devze.com 2023-04-12 16:18 出处:网络
I need to programatically send a form over POST. I have 4 fields, one checkbox 开发者_开发知识库and a submit button. how can i go about it?I use these functions assuming your question is about a forms

I need to programatically send a form over POST. I have 4 fields, one checkbox 开发者_开发知识库and a submit button. how can i go about it?


I use these functions assuming your question is about a forms application.
You can call

HttpPost(
    post_url, 
    "field_name_1", value_1,
    "field_name_2", value_2,
    ...);

Here they are:

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


This should do the trick:

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

The information, that you have checkboxes or submit buttons is not transferred. It's always name and value.


JQuery $.Post() does exactly that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号