正确获取Web响应状态代码

时间:2015-01-19 13:40:08

标签: .net vb.net winforms http httpresponse

我使用Imgur的API无意中上传了一个图片文件。

问题出在下面的函数中,我试图检索并解析Select Case上的响应代码,但如果出现问题(任何非200状态代码),那么指令{ {1}}抛出异常,因此错过了所有的选择案例,换句话说,当上传失败时我无法获取状态代码,因为Dim response As Byte() = wc.UploadValues(...)方法会抛出异常。

我如何解决这个问题?

这是我正在使用的代码:

UploadValues

1 个答案:

答案 0 :(得分:1)

首先捕获webexception,然后检查结果以查看真正的问题。

Dim response As Byte()

Try
    response = wc.UploadValues("https://api.imgur.com/3/upload.xml", values)
Catch we As WebException
    ' determine web exception from Response.GetResponseStream

    Dim resp As String
    resp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()
    ' imgUr's WebEx for Pins returns JSOn, so assume that here,
    ' but you wont know until you look at it:
    SvrResponses = CType(json.DeserializeObject(resp.ToString), 
                                    Dictionary(Of String, Object))

    ' todo examine SvrResponses to figure out the problem
Catch ex As Exception
    ' other problem
End Try