在C#中使用httpwebrequest发送'ajax'帖子请求的正确方法是什么?

时间:2015-10-03 10:58:21

标签: c# .net post web httpwebrequest

点击网页上的按钮时,firebug会生成以下请求标头(网址不会更改,因此这是一个ajax发布请求!)。我想在我的C#程序中使用httpwebrequest复制此请求。

Accept :text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding   :gzip, deflate
Accept-Language :en-US,en;q=0.5
Cache-Control   :no-cache
Connection  :keep-alive
Content-Length  :725
Content-Type    :application/x-www-form-urlencoded;charset=UTF-8
Cookie  :language=en_IN; _ga=GA1.3.184236920.1443720063;__gads=ID=9a55686039c6e6f0:T=1443720047:S=ALNI_MaWPaHUEUBgf-Zf7qdtCfl0jdtTcQ; JSESSIONID=nnMsc6NkqzXSgHXQ0DaNuHLwMl0OLChvEiv2hxBtunG22tmF_rTB!-30889781; SLB_Cookie=ffffffff09461c2745525d5f4f58455e445a4a422972; _gat_UA-57718223-1=1; _gat_UA-57718223-3=1
Faces-Request   :partial/ajax
Host    :www.example.com
Pragma  :no-cache
Referer :https://www.example.com/photography/homepage.jsf
User-Agent  :Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0

这是我到目前为止所尝试的,但它导致服务器出现错误412。我确保post_data字符串是正确的,但它仍然无效。

string post_data= "inputexForm=inputexForm&cat=senior&inputexForm%3aid=4174622&...addtab&AJAX%3AEVENTS_COUNT=1&javax.faces.partial.ajax=true";
httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.example.com/photography/homepage.jsf");
httpWebRequest.CookieContainer = cookieJar;
httpWebRequest.Referer = "https://www.example.com/photography/homepage.jsf";
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
httpWebRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
httpWebRequest.KeepAlive = true;
httpWebRequest.Connection = "keepalive";
byte[] data = UTF8Encoding.UTF8.GetBytes(post_data);
httpWebRequest.ContentLength = data.Length;
using (var stream = httpWebRequest.GetRequestStream())
{
     stream.Write(data, 0, data.Length);
     stream.Close();
}
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
webBrowser1.DocumentText = resp.ToString();

如何在C#中使用HttpWebRequest将此ajax post请求发送到服务器?

0 个答案:

没有答案