如何使用Windows.Web.Http中新的HttpClient下载图像? [英] How do I use the new HttpClient from Windows.Web.Http to download an image?

查看:75
本文介绍了如何使用Windows.Web.Http中新的HttpClient下载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Windows.Web.Http.HttpClient如何下载图像?我想使用此HttpClient,因为它可以在可移植类库中使用.

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.

推荐答案

这是我最终想到的. Windows.Web.Http.HttpClient周围没有太多文档,并且在线上的很多示例都使用诸如ReadAllBytesAsync之类的旧机制,而该机制在此HttpClient中不可用.

This is what I eventually came up with. There is not much documentation around Windows.Web.Http.HttpClient and a lot of the examples online use old mechanisms like ReadAllBytesAsync which are not available with this HttpClient.

我应该注意

I should note that this question from MSDN helped me out a lot, so thanks to that person. As the comment over there states, this guy must be the only person in the world who knows about Windows.Web.Http!

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using Windows.Storage.Streams;
using Windows.Web.Http;

public class ImageLoader
{
    public async static Task<BitmapImage> LoadImage(Uri uri)
    {
        BitmapImage bitmapImage = new BitmapImage();

        try
        {
            using (HttpClient client = new HttpClient())
            {
                using (var response = await client.GetAsync(uri))
                {
                    response.EnsureSuccessStatusCode();

                    using (IInputStream inputStream = await response.Content.ReadAsInputStreamAsync())
                    {
                        bitmapImage.SetSource(inputStream.AsStreamForRead());
                    }
                }
            }
            return bitmapImage;
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Failed to load the image: {0}", ex.Message);
        }

        return null;
    }
}

这篇关于如何使用Windows.Web.Http中新的HttpClient下载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆