Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the new HttpClient from Windows.Web.Http to download an image?

Using Windows.Web.Http.HttpClient how can I download an image? I would like use this HttpClient because it is available to use in portable class libraries.

like image 639
David Spence Avatar asked Nov 16 '14 15:11

David Spence


People also ask

In which type of application we can use HttpClient?

HttpClient is a modern HTTP client for . NET applications. It can be used to consume functionality exposed over HTTP. For example, a functionality exposed by an ASP.NET Web API can be consumed in a desktop application using HttpClient.

Why do we use HttpClient?

Why Do We Need HttpClient? The front-end of applications communicate with back-end services to get or send the data over HTTP protocol using either XMLHttpRequest interface or fetch API . This communication is done in Angular with the help of HttpClient .


2 Answers

public async void downLoadImage(string url)
{
        using (var client = new HttpClient())
        {
            var response = client.GetAsync(url).Result;
            BitmapImage bitmap = new BitmapImage();
            if (response != null && response.StatusCode == HttpStatusCode.OK)
            {
                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    using (var memStream = new MemoryStream())
                    {
                        await stream.CopyToAsync(memStream);
                        memStream.Position = 0;
                        bitmap.SetSource(memStream.AsRandomAccessStream());
                    }
                }
                HardcodedValues.profilePic = bitmap;
            }
        }
}
like image 189
Cloy Avatar answered Sep 19 '22 11:09

Cloy


In .net core web api you can use the below code

[Route("getProductImage/v1")]
    [HttpGet]
    public async Task<IActionResult> getProductImage(GetProductImageQueryParam parammodel)
    {
        using (HttpClient client = new HttpClient())
        {
            MNimg_URL = MNimg_URL + parammodel.modelname;
            HttpResponseMessage response = await client.GetAsync(MNimg_URL);
            byte[] content = await response.Content.ReadAsByteArrayAsync();
            //return "data:image/png;base64," + Convert.ToBase64String(content);
            return File(content, "image/png", parammodel.modelname);
        }
    }

here GetProductImageQueryParam is a class with input parameters

like image 45
Shigil P V Avatar answered Sep 20 '22 11:09

Shigil P V