2015-01-19 1 views
0

Imgur의 API를 사용하여 이미지 파일을 anonimouslly로 업로드하고 있습니다.웹 응답 상태 코드를 올바르게 받으십시오.

문제는 다음과 같습니다. Select Case에서 응답 코드를 검색하고 구문 분석하려고하지만, 어떤 것이 잘못되었을 경우 (200 이외의 상태 코드) 명령 Dim response As Byte() = wc.UploadValues(...)이 예외를 모두 throw합니다. 선택 사례가 누락되었습니다. 즉, UploadValues 메서드가 예외를 throw하기 때문에 업로드가 실패 할 때 상태 코드를 가져올 수 없습니다.

어떻게이 문제를 해결할 수 있습니까?

내가 사용하고 코드는 다음과 WebException이에 대한 트래핑에 의해

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

이것은 'winforms'과 어떤 관련이 있습니까? [태그 : 덜 무엇입니까?] (http://meta.stackoverflow.com/questions/281094/tags-is-less-more) –

+1

예외가 'WebException' 인 경우 잡기를 시도하고 'Response' 속성? http://msdn.microsoft.com/en-us/library/system.net.webexception.response%28v=vs.110%29.aspx – pmcoltrane

+0

제안 해 주셔서 감사합니다. – ElektroStudios

답변

1

시작, 진짜 문제가 무엇인지 확인하기 위해 결과를 검사합니다.

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 
+0

어떤 오류가 사용자에게 반환되는지 알려주세요. – Plutonix

+1

나는 잘못된 API clientId와 secretId를 사용하여 의도적으로 승인되지 않은 오류 (403)를 일으켰습니다. 나는 당신이 나에게 제안한 방식으로 어느 정도 해결 했으므로 이제는 나쁜 이미지와 같은 모든 응답을 구문 분석 할 수 있습니다. 업로드 속도 제한, 완벽하게 작동합니다!, 고맙습니다. – ElektroStudios