我正在尝试为Windows Phone 8.1 WinRT应用程序的WebView添加一些缓存。我正在使用新的IUriToStreamResolver为某些网址获取流,这在大多数情况下都可以正常工作。对于某些网址,我得到以下异常:
System.Runtime.InteropServices.COMException(0x80004005):错误HRESULT已从调用COM组件返回E_FAIL。 在System.Threading.Tasks.TaskToAsyncOperationAdapter
1.OnCompleted(AsyncOperationCompletedHandler
1 userCompletionHandler,AsyncStatus asyncStatus) 在System.Threading.Tasks.TaskToAsyncInfoAdapter4.OnCompletedInvoker(AsyncStatus status) at System.Threading.Tasks.TaskToAsyncInfoAdapter
4.TaskCompleted() ---从抛出异常的先前位置开始的堆栈跟踪结束--- 在System.Threading.Tasks.ExceptionDispatchHelper.b__1(Object edi) 在System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(对象状态) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx) 在System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() 在System.Threading.ThreadPoolWorkQueue.Dispatch() 在System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
我的UriToStreamResolver使用System.Net.HttpClient从Web获取数据并将相对URL转换为绝对URL。
using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
using Windows.Web;
namespace OfflineBrowser
{
public sealed class StreamUriWinRTResolver : IUriToStreamResolver
{
readonly System.Net.Http.HttpClient _httpClient = new System.Net.Http.HttpClient();
private readonly string _baseUrl;
public StreamUriWinRTResolver(string baseUrl)
{
_baseUrl = baseUrl;
}
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
try
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
return GetContent(path).AsAsyncOperation();
}
catch (Exception)
{
return null;
}
}
private async Task<IInputStream> GetContent(string uriPath)
{
try
{
var url2 = _baseUrl + uriPath;
var bytes = await _httpClient.GetByteArrayAsync(new Uri(url2));
IInputStream inputStream = await GetStreamForByteArray(bytes);
return inputStream;
}
catch (Exception)
{
//catch not working..
return null;
}
}
private static async Task<IInputStream> GetStreamForByteArray(byte[] content2)
{
var ras = new InMemoryRandomAccessStream();
var datawriter = new DataWriter(ras);
datawriter.WriteBytes(content2);
await datawriter.StoreAsync();
await datawriter.FlushAsync();
return ras.GetInputStreamAt(0);
}
}
}
我称之为:
private async void Button_Click(object sender, RoutedEventArgs e)
{
Uri MyUrl = WebView.BuildLocalStreamUri("MyContent", "/tvgids");
StreamUriWinRTResolver MyResolver = new StreamUriWinRTResolver("http://www.nu.nl");
WebView.NavigateToLocalStreamUri(MyUrl, MyResolver);
}
我尝试捕获异常,但这也不起作用。这可能有什么问题?我在模拟器和真实设备上都遇到了错误。谢谢你的阅读。