How to send a ‘ajax’ post request using httpwebrequest in C#?

I have the following request-header taken from firebug on clicking a button on a webpage(the url doesn’t change, so it is an ajax post request!)

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

I would like to replicate this request using httpwebrequest in my C# program.
This is what I have tried so far but it results in Error 412 from the server.

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

I have made sure that the post_data string is correct, but still it isn’t working. How can I get this ajax post request to work using HttpWebRequest in C#?


Source: .net

Leave a Reply