使用HTTP请求/响应处理错误的更好方法

时间:2012-07-08 18:22:25

标签: vb.net

我是VB新手...我使用以下代码发出HTTP请求并将响应缓冲到字符串中:

 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()

这样可以正常工作,但错误处理不好,例如,如果请求触发500响应,则VB代码遇到未处理的异常。关于如何使这段代码更好的想法?

2 个答案:

答案 0 :(得分:1)

使用HttpWebResponse.StatusCode确定服务器是否向您发送了除(可能)200(OK)之外的任何内容。

答案 1 :(得分:1)

不是使用MsgBox,而是按如下方式引发异常:

Catch ex As Exception
    Throw New Exception(ex.Message)

如果您正在从网页进行AJAX调用,则可以使用以下方法检索邮件:

Catch ex As Exception
    HttpContext.Current.Response.Write(ex.Message);
    HttpContext.Current.Response.StatusCode = 500;