Xamarin Android Url 图像获取请求收到 403 错误但不在 iOS

Xamarin Android Url image get request receiving 403 error but not on iOS

我正在开发一个将图像存储在 S3 存储桶中的 xamarin 应用程序。使用正确构造的 Url:

时,查询在 xamarin 中正常工作
https:// + BucketName + path + ".jpg?AWSAccessKeyId=keycode&Expires=expireNumber&Signature=signatureCode"  

使用时 Image.Source = urlAddress(如上格式) 图片加载正常

部分应用程序页面具有自定义渲染器,其中包含需要通过 url 地址渲染的图像。我们正在通过 url 在每个 os 级别更新图像。 iOS 使用以下代码可以正常工作:

using (var url = new NSUrl(uri))
using (var data = NSData.FromUrl(url))
      if (data != null)
            return UIImage.LoadFromData(data);

成功从Url获取图像并更新它。但是,我在 Android 上遇到了重大问题。我试过以下区域:

制作一个基本的 android url 并使用以下代码设置 imageView。这已被解释为在这里不起作用 https://forums.xamarin.com/discussion/4323/image-from-url-in-imageview

Android.Net.Uri url = Android.Net.Uri.Parse(url);

imageView.SetImageURI(url);

在同一个 link 上,用户 'rmacias' 建议使用 WebClient 通过 url 下载数据并将字节解析为 android 位图。

private Bitmap GetImageBitmapFromUrl(string url){

Bitmap imageBitmap = null;

 using (var webClient = new WebClient())
 {
      var imageBytes = webClient.DownloadData(url);
      if (imageBytes != null && imageBytes.Length > 0)
      {
           imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
      }
 }

 return imageBitmap;}

此 returns 403 禁止错误。在行 var imageBytes = webClient.DownloadData(url) 然而,相同的过程在 iOS 中运行,该字符串已经过身份验证,并且我已将身份验证超时设置为几分钟,以防加载缓慢。我还使用 .Net.Http 库调整了相同的 url 请求方法。 它在 res = (HttpWebResponse)request.GetResponse(); 崩溃并出现相同的 403 禁止错误。

我已经尝试了多种使用 WebClient 和 Http 客户端的 header 身份验证的方法。感觉它是关于 android 请求 url 数据的特定内容,因为 url 字符串中的身份验证适用于 Xamarin 图像和 ioS 代码。

我在想 android 缺少某些特定的东西?非常感谢您的帮助!

使用 HttpClient 怎么样,它可以利用 Xamarin 提供的平台特定的 HttpClientHandler?

所以像这样:

// make sure to reuse your HttpClient instance, it is a shared resource
// using it in a using() and disposing it all the time, will leave
// sockets open and bog down the connection!
private static HttpClient _httpClient;

public async Task<byte[]> GetImageDataAsync(string url)
{
    if (_httpClient == null)
    {
        // you could inject AndroidHttpClientHandler or NSUrlSessionHandler here...
        _httpClient = new HttpClient();
        // set headers etc...
    }

    var response = await _httpClient.GetAsync(url).ConfigureAwait(false);
    if (!response.IsSuccessStatusCode)
        return null;

    var result = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
    return result;
}

然后你就可以像这样使用这个平台:

var data = await GetImageDataAsync(url);
imageBitmap = BitmapFactory.DecodeByteArray(data, 0, data.Length);

于 iOS

var data = await GetImageDataAsync(url);
var imageData = NSData.FromArray(data);
imageBitmap = UIImage.LoadFromData(imageData);

还有不错的库,例如 FFImageLoading,开箱即用,具有效果,在 TableView 中加载图像等,您可以考虑将其作为替代方案。