忽略VB.NET的响应错误

时间:2015-03-15 11:03:40

标签: vb.net post request httpwebrequest

我遇到响应问题,当我收到400错误或403错误的响应时,弹出意外的事件错误。 我的问题是如何忽略这些错误?

以下是代码:

        Dim postData As String = "{""agent"": {""name"": ""Minecraft"",""version"": 1},""username"": " + TextBox1.Text + ",""password"": " + TextBox2.Text + ",""clientToken"": ""client identifier""}"
    Dim tempCookies As New CookieContainer
    Dim encoding As New UTF8Encoding
    Dim byteData As Byte() = encoding.GetBytes(postData)

    Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://authserver.mojang.com/authenticate"), HttpWebRequest)
    postReq.Method = "POST"
    postReq.KeepAlive = True
    postReq.CookieContainer = tempCookies
    postReq.ContentType = "application/json"
    postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
    postReq.ContentLength = byteData.Length
    postReq.UseDefaultCredentials = True
    postReq.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
    postReq.Credentials = CredentialCache.DefaultCredentials
    Dim postreqstream As Stream = postReq.GetRequestStream()
    postreqstream.Write(byteData, 0, byteData.Length)
    postreqstream.Close()
    Dim postresponse As HttpWebResponse


    postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
    tempCookies.Add(postresponse.Cookies)
    logincookie = tempCookies
    Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
    Dim thepage As String = postreqreader.ReadToEnd


    RichTextBox1.Text = thepage
    If thepage.Contains(":true") Then
        MsgBox("Valid")
    End If
    If thepage.Contains("ForbiddenOperationException") Then
        MsgBox("Not Valid")
    End If

2 个答案:

答案 0 :(得分:0)

在您希望忽略异常的每个语句周围,放置一个try / catch,其中'catch'为空:

Try
    ... single statement
Catch
   //empty
End Try

但是,你确定你想忽略异常吗?

答案 1 :(得分:-1)

Sub test()   
 On Error GoTo ErrHand
    'Code here

    Exit Sub
    ErrHand:
Msgbox("You got the error 91")
    If Err.Number = 91 Then Goto Errhand
    End Sub