c# - 如何使用 Windows.Web.Http 中的新 HttpClient 下载图像?

标签 c# windows-phone windows-phone-8.1 windows-8.1 portable-class-library

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

最佳答案

这是我最终想到的。关于 Windows.Web.Http.HttpClient 的文档不多,很多在线示例使用旧机制,如 ReadAllBytesAsync,此 HttpClient 不可用。

我应该注意到 this question from MSDN帮了我很多,所以感谢那个人。正如那里的评论所说,这家伙一定是世界上唯一知道 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;
    }
}

关于c# - 如何使用 Windows.Web.Http 中的新 HttpClient 下载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958829/

相关文章:

c# - C# .net 中的并行端口访问

c# - C# 方法的交换实现

c#-4.0 - JSON.Net SerializeXnode 排除某些节点

c# - 将图像从 Windows Phone 上传到 Azure Blob 存储。不创建

windows - 为 Windows Phone 8.1 创建崩溃日志

c# - 自动在 Visual Studio c# 项目中嵌入 mercurial 修订信息

xaml - Windows Phone 工具包 ListPicker 引发未处理的异常

c# - 如何在 Windows Phone 8.1 上根据系统的区域格式格式化日期/时间值?

c# - Windows Phone 更新 ListView

c# - MySQL 参数化选择查询连接表问题