2017-03-29 39 views
1

如果此問題之前已得到解答,我很遺憾,但沒有任何答案對我有幫助。我有一個事件對我的WebView:掛在較大文件上的HttpClient getAsync

private async void MainWebView_UnviewableContentIdentified(WebView sender, WebViewUnviewableContentIdentifiedEventArgs args) 
{ 
    await downloadFromUri(args.Uri).ConfigureAwait(false); 
} 

我downloadFromUri方法會嘗試下載一個文件,並將其存儲在下載文件夾,最後它會打開文件:

static async Task downloadFromUri(Uri uri) 
    { 
     var url = uri; 

     HttpClient client = new HttpClient(); 

     client.DefaultRequestHeaders.TryAppendWithoutValidation(
      "Authorization Bearer", 
       " MYTOKEN" 
      ); 

     Debug.WriteLine("Attempting GET request"); 

     var response = await client.GetAsync(url); 

     Debug.WriteLine("Got response.. checking " + response.StatusCode); 


     if (response.IsSuccessStatusCode) 
     { 
      Debug.WriteLine("Okay, we've got a response"); 
      var responseFileName = response.Content.Headers.ContentDisposition.FileName; 

      Debug.WriteLine("Filename: " + responseFileName); 

      var ManualFile = await DownloadsFolder.CreateFileAsync(responseFileName, CreationCollisionOption.GenerateUniqueName); 

      Debug.WriteLine("Creating buffer: "); 
      var buffer = await client.GetBufferAsync(url); 

      Debug.WriteLine("Writing buffer."); 
      await Windows.Storage.FileIO.WriteBufferAsync(ManualFile, buffer); 

      Debug.WriteLine("Done, opening"); 

      var openOptions = new Windows.System.LauncherOptions(); 
      openOptions.DisplayApplicationPicker = true; 

      var openFile = await Windows.System.Launcher.LaunchFileAsync(ManualFile, openOptions); 
     } 
     else 
     { 
      Debug.WriteLine(response.StatusCode.ToString()); 
     }  
    } 

的事情是,此代碼似乎可以在小型PDF或zip文件上正常工作。但是,當涉及到大於10MB的PDF文件時,應用程序只會掛在以下行:

var response = await client.GetAsync(url);

我該怎麼做才能做到這一點?提前感謝!

注意:我使用Windows.Web.Http.HttpClient而不是System.Net.Http.HttpClient。

編輯:我試過跳過client.GetAsync(url)並直接運行var buffer = await client.GetBufferAsync(url);。這也會導致死機。

+0

您是否更新了config中的maxRequestLength屬性? 您是否考慮將GetAsync更改爲ReadAsStreamAsync並將Stream寫入文件?該文件不會被下載到內存中,而是直接保存到文件中,我想。 –

回答

0

請更改代碼TO-

var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false)); 

也可參考這個 - HttpClient.GetAsync(...) never returns when using await/async

或者,您也可以使用第三方物流,這將在管理操作系統的線程池的任務中執行你的長期運行的功能。

var result = Task.Run(() => downloadFromUri(uri)).Result; 
+0

該方法.ConfigureAwait()不適用於Windows.Web.Http.HttpClient.GetAsync方法。正如我所說的,我正在使用Windows.Web.Http.HttpClient。我會嘗試你的第二個建議! –

+0

對於你的第二個建議,我得到這個異常:(從HRESULT異常:0x8001010E(RPC_E_WRONG_THREAD))' –

+1

哦,我明白了。你可以使用'System.Net.Http.HttpClient'嗎?或者有特定的原因。如果您仍然想要使用當前實現,則可以使用取消令牌和超時。最好設置一個超時以避免無限期等待。請參閱http://stackoverflow.com/questions/19535004/windows-web-http-httpclient-timeout-option –

2

也許對於較大的文件,最好使用

Windows.Networking.BackgroundTransfer

命名空間,如BackgroundDownloader

+0

據我所知,你不能找到背景下載的文件名。這是強制性的。或者我錯過了什麼? –