使用 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/