I’ve created VB code to download files from a web site through the use of
HTTPWebRequest, HTTPWebResponse and BinaryReader.
The HTTPWebRequest has a TimeOut property to limit how long it waits for a
corresponding HTTPWebResponse . This works just fine. However, the timeout
does not appear to apply to a BinaryReader created from the HTTPWebResponse .
I’ve had instances where the procedures will hang indefinitely during the
download.
Is there a means to force a “time out” on the BinaryReader?
CODE EXAMPLE:
In this example, parameters are posted to the web site and a file retrieved.
No proxy is involved.
Dim myHTTPWebReques t as HTTPWebRequest
Dim myHTTPWebRespon se as HTTPWebResponse
Dim sbPostData as new Stringbuilder
Dim sbWebAddress as new stringbuilder
Dim myTextWriter As TextWriter
Dim myBinaryReader As BinaryReader
Dim myBinaryWriter as BinaryWriter
Dim intBuffer As Integer = 65536
Dim byteBuffer() As Byte
Const _cnstHTTP_Accep t_All As String = "image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg, application/vnd.ms-excel,
application/vnd.ms-powerpoint, application/msword,
application/x-shockwave-flash, */*"
Const _cnstHTTP_Conte ntType_URLEncod ed As String =
"applicatio n/x-www-form-urlencoded"
Const _cnstHTTP_Metho d_Post As String = "POST"
Const _cnstHTTP_UserA gent As String = "Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1; .NET CLR 1.1.4322)"
‘ Create HTTPWebRequest
‘
With sbWebAddress
.remove(0, .Length)
.append(www.bogusaddress.com/download)
End
‘ Set post data
‘
With sbPostData
.remove(0, .length)
.append(“Begi n=12/1/2004”)
.append(“&” )
.append(“EndD ate=12/2/2004”)
End with
‘ Create web request
‘
myHTTPWebReques t = CType(HttpWebRe quest.Create(sb WebAddress.ToSt ring),
HttpWebRequest)
' Set parms
‘
With myHTTPWebReques t
..Accept = _cnstHTTP_Accep t_All
..ContentLength = sbPostData.Leng th
..ContentType = _cnstHTTP_Conte ntType_URLEncod ed
..KeepAlive = True
..Method = _cnstHTTP_Metho d_Post
..Referer = "http://www.bogusaddres s.com/referer"
..Timeout = 60000
..UserAgent = _cnstHTTP_UserA gent
..Headers.Add(" Accept-Encoding", "gzip, deflate")
..Headers.Add(" Accept-Language", "en-us")
..Headers.Add(" Cache-Control", "no-cache")
End With
' Send parms
'
myTextWriter = CType(New StreamWriter(my HTTPWebRequest. GetRequestStrea m),
TextWriter)
myTextWriter.Wr ite(sbPostData. ToString)
myTextWriter.Cl ose()
myHTTPWebRespon se = CType(myHTTPWeb Request.GetResp onse, HttpWebResponse )
‘ Get file stream
'
myBinaryReader = New BinaryReader(my HTTPWebResponse .GetResponseStr eam)
myBinaryWriter = New BinaryWriter(Ne w FileStream(“c :\temp\bogus.tx t”,
FileMode.Create ))
' Read/write
'
byteBuffer = myBinaryReader. ReadBytes(intBu ffer)
‘ As best as I can tell, this is where it hangs
‘
Do While byteBuffer.Leng th > 0
myBinaryWriter. Write(byteBuffe r)
myBinaryWriter. Flush()
byteBuffer = myBinaryReader. ReadBytes(intBu ffer)
Loop
myBinaryWriter. Close
myHTTPWebRespon se.Close