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

2019-09-04 04:59发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-04 05:57

seems i had to change

    Catch ex As Exception
    MsgBox(ex.ToString)
Finally

To

Catch ex As System.Net.WebException
        MsgBox(ex.ToString)
Finally
查看更多
登录 后发表回答