If you are already familiar with the basics of HttpWebRequest and HttpWebResponse classes for WebCommunication, the following code can help you get the response using HttpWebRequest .
HttpWebRequest hRequest = (HttpWebRequest)WebRequest.Create("[email protected]");
This is the basic way to get HttpWebRequest . It is fastest way but difficult to implement for downloading of content to our local machine.
The following code will download the content to our local location.
using (response = (HttpWebResponse)hRequest.GetResponse()) { /*Download the file to the fullFileName location */ Stream streamResponse = response.GetResponseStream(); if (streamResponse != null) { byte[] inBuf = new byte[response.ContentLength]; int bytesToRead = System.Convert.ToInt32(inBuf.Length); int bytesRead = 0; while (bytesToRead > 0) { int n = streamResponse.Read(inBuf, bytesRead, bytesToRead); if (n == 0) { break; } bytesRead += n; bytesToRead -= n; } var fstr = new FileStream(fullFileName, FileMode.OpenOrCreate, FileAccess.Write); fstr.Write(inBuf, 0, bytesRead); streamResponse.Close(); streamResponse.Dispose(); fstr.Close(); fstr.Dispose(); } }
The Same Request as well as downloading can be done very easily using another class System.Net.WebClient in one go
As :
using (var wc = new WebClient()) { wc.DownloadFile("[email protected]", fullFileName); }
We can use the WebClient Class easily, but I found some pitfalls in using this : 1) The WebClient maintains http “keep-alives=true” by default. This is not desirable for the quick connection the application requires.
2) The Timeout period is not specified for the response period.
The following can be controlled using the following using HttpWebRequest and HttpWebResponse
As:
hRequest.Timeout = 5000; // 5 seconds // subsequent stream read timeout (milliseconds) - default is 300,000 milliseconds (5 min.) hRequest.ReadWriteTimeout = 5000; // 5 seconds hRequest.KeepAlive = false; // to prevent open HTTP connection leak