使用Windows.Web.Http.HttpClient
如何下载图片?我想使用这个HttpClient,因为它可用于可移植类库。
答案 0 :(得分:7)
这是我最终想出来的。围绕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;
}
}
答案 1 :(得分:2)
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;
}
}
}
答案 2 :(得分:1)
在.net core web api中,您可以使用以下代码
[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);
}
}
这里GetProductImageQueryParam是一个带输入参数的类
答案 3 :(得分:0)
更新了8.1 - 10.
public async static Task<BitmapImage> LoadImage(Uri uri)
{
BitmapImage bitmapImage = new BitmapImage();
try
{
using (Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient())
{
using (var response = await client.GetAsync(uri))
{
response.EnsureSuccessStatusCode();
using (MemoryStream inputStream = new MemoryStream())
{
await inputStream.CopyToAsync(inputStream);
bitmapImage.SetSource(inputStream.AsRandomAccessStream());
}
}
}
return bitmapImage;
}
catch (Exception ex)
{
Debug.WriteLine("Failed to load the image: {0}", ex.Message);
}
return null;
}