I am new to VB…I am using the following code to make an HTTP request and buffer the response into a String:
Try
myHttpWebRequest = CType(WebRequest.Create(strUrl), HttpWebRequest)
myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
receiveStream = myHttpWebResponse.GetResponseStream()
encode = System.Text.Encoding.GetEncoding("utf-8")
sr = New StreamReader(receiveStream, encode)
Do Until sr.Peek = -1
strLine = String.Concat(strLine, sr.ReadLine)
arrBuff.Add(strLine)
Loop
Catch ex As System.Net.WebException
MsgBox(ex.Message)
Finally
myHttpWebResponse.Close()
End Try
sr.Close()
This works fine, but errors are not handled well, for example if the request triggers a 500 response the VB code encounters an unhandled exception. Any thoughts on how to make this code better?
Use the
HttpWebResponse.StatusCodeto determine if the server has sent you anything but a (probably) 200 (OK).