VB.Net JSON From URL To Textbox How Can I Handle E

2019-09-04 05:12发布

问题:

My JSON String Returned

{

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

My Code At The Moment

    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

But when i get an error like 404 i get an exception

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

this happens at the line

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

please could you advise me on how i can handle this error and output a message to a messagebox

Thanks

回答1:

seems i had to change

    Catch ex As Exception
    MsgBox(ex.ToString)
Finally

To

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