forms - How to simulate HTTP POST programatically in ASP.NET? -


i need simulate http post programatically, i.e., need generate request post variables , send page.

to clarify, need simulate behaviour of regular post, not whole thing programatically. need fill in request in same way filled if form post happening, , send browser page expects post.

here 1 way it.

you send method url , name/value parameters in form of namevaluecollection. method makes http post on endpoint , returns response string.

of course depending on what/why you're doing , how many times method called, there maybe other alternatives. until provide more information on specific needs, method enough.

the method below uses tasks (.net 4.0) , async methods faster synchronous method next code listing if you're making multiple calls in loop example.

static string getwebresponse(string url, namevaluecollection parameters) {   var httpwebrequest = (httpwebrequest)webrequest.create(url);   httpwebrequest.contenttype = "application/x-www-form-urlencoded";   httpwebrequest.method = "post";    var sb = new stringbuilder();   foreach (var key in parameters.allkeys)     sb.append(key + "=" + parameters[key] + "&");   sb.length = sb.length - 1;    byte[] requestbytes = encoding.utf8.getbytes(sb.tostring());   httpwebrequest.contentlength = requestbytes.length;    using (var requeststream = httpwebrequest.getrequeststream())   {     requeststream.write(requestbytes, 0, requestbytes.length);     requeststream.close();   }    task<webresponse> responsetask = task.factory.fromasync<webresponse>(httpwebrequest.begingetresponse, httpwebrequest.endgetresponse, null);   using (var responsestream = responsetask.result.getresponsestream())   {     var reader = new streamreader(responsestream);     return reader.readtoend();   } } 

you use webclient (it's bit simpler). method expects post parameters string in form

name1=value1&name2=value2&name3=value3 

etc. if use method sure pass in parameters such or modify implementation code above.

static string httppost(string url, string parameters)  {    var req = system.net.webrequest.create(url);            req.contenttype = "application/x-www-form-urlencoded";    req.method = "post";    byte[] bytes = system.text.encoding.ascii.getbytes(parameters);    req.contentlength = bytes.length;    system.io.stream os = req.getrequeststream ();    os.write (bytes, 0, bytes.length);    os.close ();    system.net.webresponse resp = req.getresponse();    if (resp== null)      return null;    var sr = new streamreader(resp.getresponsestream());    return sr.readtoend().trim(); } 

Comments

Popular posts from this blog

Javascript line number mapping -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -