2012-07-08 119 views
0

我是新来的VB ...我使用下面的代码,以使一个HTTP请求和缓冲响应为一个字符串错误方式:更好地处理与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代码遇到未处理的异常。关于如何使这段代码更好的想法?

回答

1

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

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;