Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...