[转帖]HttpClient:下载到本地文件_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 2511 | 回复: 0   主题: [转帖]HttpClient:下载到本地文件        下一篇 
nini
注册用户
等级:新兵
经验:56
发帖:63
精华:0
注册:2011-12-16
状态:离线
发送短消息息给nini 加好友    发送短消息息给nini 发消息
发表于: IP:您无权察看 2014-12-15 14:30:17 | [全部帖] [楼主帖] 楼主

内容下载到本地文件,是一种常见的事。HttpClient的当前版本还没有提供保存内容到一个文件,但这个示例显示了如何扩展HttpClient的检索与阅读内容的新方式使用HttpClient的开箱即用的支持。这个范例也可用代码库。

ReadAs扩展方法

    HttpContent类包含的内容被发送到客户端(在PUT的情况下,POST等),以及数据被读取从服务器的响应。基本System.Net.Http NuGet包提供了阅读的内容作为一个流,一个字符串,或一个字节数组的支持,使用一个

.HttpContent.ReadAsStringAsync
.HttpContent.ReadAsStreamAsync
.HttpContent.ReadAsByteArrayAsync


    延长一个HttpContent可以消耗的方式是通过ReadAs *扩展方法。System.Net.Formatter NuGet包提供一个额外ReadAs的的的一套方法,在同一时间阅读和反序列化数据。此示例显示了如何添加一个简单的ReadAsFileAsync扩展方法,但地板是任意数量的阅读内容的方式公开。

LoadIntobufferAsync


    在一般情况下,当你从HttpContent读取数据时,它被消耗,这意味着它不能再被读取(例如,当你读一个非可查找流)。不过,如果你想成为能够阅读的内容多次,那么你可以使用的LoadIntoBufferAsync的方法来做到这一点。这将导致内容读入内部缓冲区,以便它可以消耗多次,无需再通过网络检索。

1: static void Main(string[] args)
2: {
3: HttpClient client = new HttpClient();
4:
5: // Send asynchronous request


发送异步请求

6: client.GetAsync(_address).ContinueWith(
7: (requestTask) =>
8: {
9: // Get HTTP response from completed task.


                      获取从完成任务的HTTP响应。

10:             HttpResponseMessage response = requestTask.Result;
11:
12:             // Check that response was successful or throw exception


检查该响应是成功还是抛出异常

13:             response.EnsureSuccessStatusCode();
14:
15:             // Read content into buffer


读入缓冲区的内容

16:             response.Content.LoadIntoBufferAsync();
17:
18:             // The content can now be read multiple times using any ReadAs* extension method 内容现在可以被读取多次使用任何ReadAs *扩展方法
19:         });
20:
21:     Console.WriteLine("Hit ENTER to exit...");// 回车退出...
22:     Console.ReadLine();
23: }
ReadAsFileAsync


    首先,我们就HttpContent的ReadAsFileAsync扩展方法提供支持阅读的内容,并直接存储在本地文件:

1: public static class HttpContentExtensions
2: {
      3: public static Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite)
      4: {
            5: string pathname = Path.GetFullPath(filename);
            6: if (!overwrite && File.Exists(filename))
            7: {
            8: throw new InvalidOperationException(string.Format("File {0} already exists.", pathname));
            9: }
            10:
            11: FileStream fileStream = null;
            12: try
            13: {
                  14: fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None);
                  15: return content.CopyToAsync(fileStream).ContinueWith(
                  16: (copyTask) =>
                  17: {
                        18: fileStream.Close();
                  19: });
            20: }
            21: catch
            22: {
                  23: if (fileStream != null)
                  24: {
                        25: fileStream.Close();
                  26: }
                  27:
                  28: throw;
            29: }
      30: }
31: }


下载谷歌地图

    最后,我们把两者结合起来-在这种情况下,我们下载谷歌地图的图像,并在默认的图像浏览器打开它(如果你没有一个图像浏览器,然后打开下载的映像会失败,但不会改变下载的一部分):

1: /// <summary>
2: /// Downloads a Redmond map from Google Map, saves it as a file and opens the default viewer.
3: /// </summary>
4: class Program
5: {
      6: static string _address = "http://maps.googleapis.com/maps/api/staticmap?center=Redmond,WA&zoom=14&size=400x400&sensor=false";
      7:
      8: static void Main(string[] args)
      9: {
            10: HttpClient client = new HttpClient();
            11:
            12: // Send asynchronous request
            13: client.GetAsync(_address).ContinueWith(
            14: (requestTask) =>
            15: {
                  16: // Get HTTP response from completed task.
                  17: HttpResponseMessage response = requestTask.Result;
                  18:
                  19: // Check that response was successful or throw exception
                  20: response.EnsureSuccessStatusCode();
                  21:
                  22: // Read response asynchronously and save to file
                  23: response.Content.ReadAsFileAsync("output.png", true).ContinueWith(
                  24: (readTask) =>
                  25: {
                        26: Process process = new Process();
                        27: process.StartInfo.FileName = "output.png";
                        28: process.Start();
                  29: });
            30: });
            31:
            32: Console.WriteLine("Hit ENTER to exit...");
            33: Console.ReadLine();
      34: }
35: }


--转自 北京联动北方科技有限公司




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论