G
Guest
Hi,
I am trying to download a file from a web page in code. I cannot use the System.Net.WebClient DownloadFile method because in order to get the file i must POST a request with form fields. Took a wild-*ss_guess at how to do it but it doesn't work. (see code below) I get a error 400 response (bad request). Any advice on this would be greatly appreciated.
WebRequest request =
System.Net.WebRequest.Create("http://oaspub.epa.gov/pls/ats/arr_txt");
WebResponse response;
NameValueCollection formCollection = new NameValueCollection();
Stream stream;
FileStream fs;
byte[] buffer;
int copyByte = 0;
fs = File.Create(@"C:\aaa.txt");
formCollection.Add("STATE_CD","USA");
formCollection.Add("LOWID","000000000000");
formCollection.Add("HIGHID","999999999999");
formCollection.Add("ACCTNAME","%");
formCollection.Add("REPNAME","%");
buffer = System.Text.Encoding.ASCII.GetBytes(formCollection.ToString());
request.Method = "POST";
request.ContentLength = buffer.Length;
stream = request.GetRequestStream();
stream.Write(buffer,0,buffer.Length);
stream.Close();
stream = request.GetResponse().GetResponseStream();
copyByte = stream.ReadByte();
while(copyByte != -1)
{
fs.WriteByte((byte)copyByte);
copyByte = stream.ReadByte();
}
stream.Close();
fs.Close();
I am trying to download a file from a web page in code. I cannot use the System.Net.WebClient DownloadFile method because in order to get the file i must POST a request with form fields. Took a wild-*ss_guess at how to do it but it doesn't work. (see code below) I get a error 400 response (bad request). Any advice on this would be greatly appreciated.
WebRequest request =
System.Net.WebRequest.Create("http://oaspub.epa.gov/pls/ats/arr_txt");
WebResponse response;
NameValueCollection formCollection = new NameValueCollection();
Stream stream;
FileStream fs;
byte[] buffer;
int copyByte = 0;
fs = File.Create(@"C:\aaa.txt");
formCollection.Add("STATE_CD","USA");
formCollection.Add("LOWID","000000000000");
formCollection.Add("HIGHID","999999999999");
formCollection.Add("ACCTNAME","%");
formCollection.Add("REPNAME","%");
buffer = System.Text.Encoding.ASCII.GetBytes(formCollection.ToString());
request.Method = "POST";
request.ContentLength = buffer.Length;
stream = request.GetRequestStream();
stream.Write(buffer,0,buffer.Length);
stream.Close();
stream = request.GetResponse().GetResponseStream();
copyByte = stream.ReadByte();
while(copyByte != -1)
{
fs.WriteByte((byte)copyByte);
copyByte = stream.ReadByte();
}
stream.Close();
fs.Close();