简体   繁体   English

httpclient GetAsync 不适用于大内容

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

I am trying to download the string content from an endpoint in question using xamarin and http requests.我正在尝试使用 xamarin 和 http 请求从相关端点下载字符串内容。 The endpoint I'm supporting with python flask, as well as the content of the page, which is similar to this:我支持的端点为 python flask,以及页面内容,类似于:

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

When there are not many lines in the content of the page, I can access the content and save it to a file inside the android device.当页面内容行数不多时,我可以访问内容并将其保存到android设备内部的文件中。 When the content is very long, with many lines, the application simply closes.当内容很长,有很多行时,应用程序就会关闭。

My code is as follows:我的代码如下:

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.";
    }
}

I did add .ConfigureAwait(false) to each await line, but it didn't work... What am I doing wrong?我确实将.ConfigureAwait(false)添加到每个等待行,但它没有用......我做错了什么?

Thank you!谢谢!

When you used HttpClient to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering.当您使用HttpClient下载大量数据(50 兆字节或更多)时,应用程序应该 stream 这些下载并且不使用默认缓冲。 If the default buffering is used the client memory usage will get very large, potentially resulting in substantially reduced performance.如果使用默认缓冲,客户端 memory 使用量将变得非常大,可能导致性能大幅下降。

You could try to get the response body and load into 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