Get Web Response Status Code properly

2019-08-31 05:23发布

问题:

I'm using Imgur's API to upload an image file anonimouslly.

The problem is with the function below, I'm trying to retrieve and parse the response code on the Select Case, but if something goes wrong (any non-200 status-code) then the instruction Dim response As Byte() = wc.UploadValues(...) throws an exception so all the select case is missed, or in other words, I cannot get the status code when the uploading fails because the UploadValues method throws an exception.

How I could fix this issue?

This is the code that I'm using:

    Public Function UploadImage(ByVal img As String) As ImgurImage

        Try

            ' Create a WebClient. 
            Using wc As New WebClient()

                ' Read the image.
                Dim values As New NameValueCollection() From
                    {
                        {"image", Convert.ToBase64String(File.ReadAllBytes(img))}
                    }

                ' Set the Headers.
                Dim headers As New NameValueCollection() From
                    {
                        {"Authorization", String.Format("Client-ID {0}", Me.ClientId)}
                    }

                ' Add the headers.
                wc.Headers.Add(headers)

                ' Upload the image, and get the response.
                Dim response As Byte() = wc.UploadValues("https://api.imgur.com/3/upload.xml", values)

                ' Read the response (Converting Byte-Array to Stream).
                Using sr As New StreamReader(New MemoryStream(response))

                    Dim serverResponse As String = sr.ReadToEnd
                    Dim xdoc As New XDocument(XDocument.Parse(serverResponse))
                    Dim status As ImgurStatus = Nothing

                    status = Me.GetResultFromStatus(Convert.ToInt32(xdoc.Root.LastAttribute.Value.ToString))

                    Select Case status

                        Case ImgurStatus.Success
                            Return New ImgurImage(New Uri(xdoc.Descendants("link").Value))

                        Case ImgurStatus.AccessForbidden
                            RaiseEvent OnAccessForbidden(Me, ImgurStatus.AccessForbidden)

                        Case ImgurStatus.AuthorizationFailed
                            RaiseEvent OnAuthorizationFailed(Me, ImgurStatus.AuthorizationFailed)

                        Case ImgurStatus.BadImageFormat
                            RaiseEvent OnBadImageFormat(Me, ImgurStatus.BadImageFormat)

                        Case ImgurStatus.InternalServerError
                            RaiseEvent OnInternalServerError(Me, ImgurStatus.InternalServerError)

                        Case ImgurStatus.PageIsNotFound
                            RaiseEvent OnPageIsNotFound(Me, ImgurStatus.PageIsNotFound)

                        Case ImgurStatus.UploadRateLimitError
                            RaiseEvent OnUploadRateLimitError(Me, ImgurStatus.UploadRateLimitError)

                        Case ImgurStatus.UnknownError
                            RaiseEvent OnUnknownError(Me, ImgurStatus.UnknownError)

                    End Select

                End Using '/ sr As New StreamReader

            End Using '/  wc As New WebClient()

        Catch ex As Exception
            RaiseEvent OnUnknownError(Me, ImgurStatus.UnknownError)

        End Try

        Return Nothing

    End Function

回答1:

Start by trapping for a webexception, then examine the result to see what the real problem is.

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