簡體   English   中英

httpclient GetAsync 不適用於大內容

[英]httpclient GetAsync doesn't work for large content

我正在嘗試使用 xamarin 和 http 請求從相關端點下載字符串內容。 我支持的端點為 python flask,以及頁面內容,類似於:

[{"name":"test1","timestamp":12312,"type":"ultrasonic","value":65535}, 
{"name":"test2","timestamp":3123123,"type":"ultrasonic","value":65535}...]

當頁面內容行數不多時,我可以訪問內容並將其保存到android設備內部的文件中。 當內容很長,有很多行時,應用程序就會關閉。

我的代碼如下:

public async Task<string> GetNews()
{
    List<string> valores = new List<string>();    
    var response = await client.GetAsync(get_url);    
    var responseData = await response.Content.ReadAsStringAsync();    
    string nome = DateTime.Now.ToString("HH:mm:ss");    
    //creating the subsequent file
    string filename = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Personal),
        "Sensor File - " + nome + ".json");
    //inserting the content of the GET into the generated text file
    System.IO.File.WriteAllText(filename, responseData);
    return null;
}
public async void Download_Clicked(object sender, EventArgs e)
{
    try
    {
        await GetNews(); 
        //informing in the first label the directory of the saved file
        lb.Text = "File saved successfully!";
    }
    catch
    {
        lb.Text = "Connection not possible, enter the correct URL.";
    }
}

我確實將.ConfigureAwait(false)添加到每個等待行,但它沒有用......我做錯了什么?

謝謝!

當您使用HttpClient下載大量數據(50 兆字節或更多)時,應用程序應該 stream 這些下載並且不使用默認緩沖。 如果使用默認緩沖,客戶端 memory 使用量將變得非常大,可能導致性能大幅下降。

您可以嘗試獲取響應主體並加載到 memory。

using (var response = await client.GetAsync(get_url))
    using (Stream streamToReadFrom =
        await response.Content.ReadAsStreamAsync())
    {
            ...........
            //string fileToWriteTo = Path.GetTempFileName();
            //using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
            //{
            //    await streamToReadFrom.CopyToAsync(streamToWriteTo);
            //}
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM