Download number of bytes from websource

2019-01-28 12:55发布

问题:

I'm trying to download a number of bytes from websource using HttpWebRequest (can be any different way - I've tried WebRequest, HttpClient ...) on Windows Phone 8.1 Runtime - complete code:

private async void Download1000_Click(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("Download Started");
    HttpWebRequest longRequest = (HttpWebRequest)WebRequest.Create(new Uri(@"http://s3.amazonaws.com/dnr/dotnetrocks_0986_enterprise_sharepoint.mp3"));
    longRequest.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(); // prevent caching the whole file
    longRequest.AllowReadStreamBuffering = false;
    using (WebResponse myResponse = await longRequest.GetResponseAsync())
    using (Stream myStream = myResponse.GetResponseStream())
    {
        int bytesRead = 0;
        byte[] myBuffer = new byte[1000];
        Stopwatch newWatch = new Stopwatch();
        newWatch.Start();
        while ((bytesRead = await myStream.ReadAsync(myBuffer, 0, 1000)) > 0)
            Debug.WriteLine(bytesRead.ToString() + " bytes read. Elapsed time: " + newWatch.Elapsed.TotalSeconds.ToString("0.000000") + " seconds");
    }
    Debug.WriteLine("Download Finished");
}

The problem - the code is working, but OS is somehow preventing reading small amount of bytes (even I've disabled AllowReadStreamBuffering) - it seems that it downloads the whole file to some cache (?) and then runs the while loop. It looks like this:

As you can see - the first amount of bytes appears after 22 seconds - the file was downloaded whole. Contrary when I bulid the same code (copy-paste) on Windows Phone 8.1 Silverligh, and run on the same device - it runs as it should:

Is there any method to download number of bytes on WP8.1 Runtime, without downloading the whole file first?

回答1:

Here is a last resort idea - use sockets! It's very uncool, I know.

If what you need is not super complex, you can mix something up using these two: .NET Http socket library and TcpClient for WP. I recently needed this for a Windows Phone 8.0 app, so I used these libraries and it is working fine.

Edit - Demo project

Here's a demo project that does what I just suggested. It's nothing epic, but it seems to do the trick. If you don't need something too complex, it should work fine.

Offtopic - why I needed sockets

Recently I had an issue with all other available options for http requests - they all need the UI thread to be free in order to work (at least in Windows Phone, not sure about WinRT). That is - they actually do something in the UI thread even if you use them from another thread. And that is generally fine... except in my situation I really needed to block the UI thread.



回答2:

It's a bug in SDK. Reported to Microsoft team by email and got confirmed by one of their engineers. Hope it will be fixed in next release...