编程发送带有POST形式 [英] programatically send a form with POST

查看:117
本文介绍了编程发送带有POST形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于编程发送带有POST形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆