我发现以下示例以异步方式下载网页(字符串):
let getImage (imageUrl:string) =
async {
try
let req = WebRequest.Create(imageUrl) :?> HttpWebRequest
req.UserAgent <- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
req.Method <- "GET";
req.AllowAutoRedirect <- true;
req.MaximumAutomaticRedirections <- 4;
let! response1 = req.AsyncGetResponse()
let response = response1 :?> HttpWebResponse
use stream = response.GetResponseStream()
use streamreader = new System.IO.StreamReader(stream)
return! streamreader.AsyncReadToEnd() // .ReadToEnd()
with
_ -> return "" // if there's any exception, just return an empty string
}
返回一个字符串。但是,我需要异步下载一个在线图像(一个字节数组)。
有人能给我一些提示吗?
答案 0 :(得分:1)
您可以直接从流中读取字节。 StreamReader适用于字符串。它实际上继承了TextReader。另外看一下使用BinaryReader,它可以在字节上工作。
(因为你把它标记为C#我会在C#中编写我的代码示例。)
Stream s = response.GetResponseStream()
MemoryStream memStream = new MemoryStream();
int bytesRead;
byte[] buffer = new byte[0x1000];
for (bytesRead = s.Read(buffer, 0, buffer.Length); bytesRead > 0; bytesRead = s.Read(buffer, 0, buffer.Length))
{
memStream.Write(buffer, 0, bytesRead);
}
s.Close();
return memStream.ToArray();
答案 1 :(得分:1)
也许你可以将我的答案用于另一个问题(here)。它要求谷歌图表API提供图像(URL)并将字节转换为位图。
相关代码:
async {
let req = HttpWebRequest.Create(..URI HERE..)
let! response = req.AsyncGetResponse()
return new Bitmap(response.GetResponseStream())
} |> Async.RunSynchronously
答案 2 :(得分:0)
使用http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx
然后你只需要GetResponseStream并读取字节。
答案 3 :(得分:-1)
您可以将流转换为像这样的字节数组(C#)
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream(stream))
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
var bytes = ms.ToArray();
}