.net - How do I download a PDF from an HTML webpage-submitted POST form using C#? -
i'm trying programmatically download pdf document c# windows form application. right now, i've got far enough unique url each page goes download pdf.
each link webpage submits form via post page loaded
function window_onload() { form1.submit(); }
then pdf starts downloading. stop pdf downloading , save automatically local machine. reason want because there around 15-20 pdfs need download every week.
i use httpwebrequest object.
depending on size pdfs, , response time of servers asynchronously or synchronously. synchronous flavor using getresponse()
method.
void dopdfdownload(string strmyurl, string strpostdata, string savelocation) { //create request var wr = (httpwebrequest)webrequest.create(myurl); wr.method = "post"; wr.contentlength = strpostdata.length; //identify content type... strpostdata should url encoded per next //declaration wr.contenttype = "application/x-www-form-urlencoded"; //just measure, set cookies if necessary session management, etc. wr.cookiecontainer = new cookiecontainer(); using(var sw = new streamwriter(wr.getrequeststream())) { sw.write(strpostdata); } var resp = wr.getresponse(); //feeling rather lazy @ point, if need further code writing //response stream file stream, can provide. //... }
the following little method copy/paste linqpad idea of how these classes work.
void dospeedtestdownloadfromfcc() { string strmyurl = "http://data.fcc.gov/api/speedtest/find?latitude=38.0&longitude=-77.5&format=json"; //create request var wr = (httpwebrequest)webrequest.create(strmyurl); wr.contentlength = strpostdata.length; //note changed method webservice's standard. //no content type on requests. wr.method = "get"; //just measure, set cookies if necessary session management, etc. wr.cookiecontainer = new cookiecontainer(); var resp = wr.getresponse(); //... using(streamreader sr = new streamreader(resp.getresponsestream())) { //here write file disk using preferred method //in linq pad, outputs text console. sr.readtoend().dump(); } }
Comments
Post a Comment