VB.Net JSON从URL到Textbox如何处理错误?

时间:2014-02-22 02:25:36

标签: json url http-status-code-404

我的JSON字符串已返回

{

"name": "username",
"place": {
  "name": "placename",
}    

我的代码

    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader

    Try

        request = DirectCast(WebRequest.Create("http://my-json.com/json"), HttpWebRequest)

        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())

        Dim rawresp As String
        rawresp = reader.ReadToEnd()

        Dim jResults As JObject = JObject.Parse(rawresp)
        usernameTextbox.text = jResults("name").ToString()
        placenameTextbox.text = jResults("place")("name").ToString()

    Catch ex As Exception
        MsgBox(ex.ToString)
    Finally
        If Not response Is Nothing Then response.Close()

    End Try

但是当我得到像404这样的错误时我会得到一个异常

system.net.webexception: The server returned an error (404) Not Found.

这发生在

response = DirectCast(request.GetResponse(), HttpWebResponse)

请您告诉我如何处理此错误并将消息输出到消息框

由于

1 个答案:

答案 0 :(得分:0)

似乎我不得不改变

    Catch ex As Exception
    MsgBox(ex.ToString)
Finally

Catch ex As System.Net.WebException
        MsgBox(ex.ToString)
Finally