0

I'm searching for a solution in C# or else VB.Net for this problem.

Using a WebClient I would like to retrieve the server response of UploadValuesAsync method asynchronously but I can't figure it out how to do it.

Basically I want to do the same done in this question, get the response code as Integer (but asynchronouslly): Get Web Response Status Code properly

Example code:

The problem with the code below is the same problem exposed in the other question that I linked, it throws an exception if the e.result property is not ok then I can't parse any other status code than a 200 code because that exception.

I've searched for a Response property on the e.Error exception but I didn't found anything, so I'm not able to proceed.

AddHandler wc.UploadValuesCompleted, AddressOf WC_UploadValuesCompleted
wc.UploadValuesAsync(New Uri("https://api.imgur.com/3/upload.xml"), values)

Then:

Private Sub WC_UploadValuesCompleted(ByVal sender As Object, ByVal e As UploadValuesCompletedEventArgs)

   If Not e.Cancelled Then

        Dim responseAsync As Byte() = e.Result

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

            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 ' 200
                    Return New ImgurImage(New Uri(xdoc.Descendants("link").Value))

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

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

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

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

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

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

                Case ImgurStatus.UnknownError ' -0
                    RaiseEvent OnUnknownError(Me, ImgurStatus.UnknownError)
                    Return Nothing

            End Select

        End Using '/ sr As New StreamReader

   End If

End Sub
3
  • 1
    HttpClient class has very nice methods to do it asynchronously. Commented Jan 19, 2015 at 18:45
  • Thanks for comment, but I don't know how to. Commented Jan 19, 2015 at 18:49
  • dont try and pass the exception result as an event arg. parse it on the spot and convert to a result value. the (original) RequestToken method already has code doing just that. Commented Jan 19, 2015 at 19:22

1 Answer 1

1

Below code worked for me (using Json.Net):

async private void button1_Click(object sender, EventArgs e)
{
    var response = await UploadToImgUrl(filename, client_id);
}

async Task<ImgUrl.Response> UploadToImgUrl(string fname, string client_id)
{
    string endPoint = "https://api.imgur.com/3/upload";
    var data = Convert.ToBase64String(File.ReadAllBytes(fname));

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Client-ID " + client_id);    
        var resp = await client.PostAsJsonAsync(endPoint, new { image = data, type= "base64", name = new FileInfo(fname).Name });
        var content  = await resp.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<ImgUrl.Response>(content);
    }
}

public class ImgUrl
{
    public class Data
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public int Datetime { get; set; }
        public string Type { get; set; }
        public bool Animated { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int Size { get; set; }
        public int Views { get; set; }
        public int Bandwidth { get; set; }
        public string Deletehash { get; set; }
        public string Name { get; set; }
        public string Link { get; set; }
    }

    public class Response
    {
        public Data Data { get; set; }
        public bool Success { get; set; }
        public int Status { get; set; }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.