一、后台下载/上传

1、简介

  使用BackgroundTransferGroup可以十分方便操作上传及下载文件,BackgroundDownloader和BackgroundUploader类中的方法提供一系列方法交互这一过程,因此我们也可以利用live tile或toast显示传输的状态。

2、下载代码

代码一:

async void DownloadFile(Uri sourceUri, string destFilename)
{
cts = new CancellationTokenSource();
StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
destFilename, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(sourceUri, destinationFile); try
{
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
// Start the download and attach a progress handler.
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
catch (TaskCanceledException) { /* User cancelled the transfer */ }
catch (Exception ex) { /* ... */ }
}

代码二:

private void CancelAll_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
cts.Dispose();
cts = new CancellationTokenSource(); // Re-create the CancellationTokenSource for future downloads.
} private void DownloadProgress(DownloadOperation download)
{
double percent = ;
if (download.Progress.TotalBytesToReceive > )
percent = download.Progress.BytesReceived * / download.Progress.TotalBytesToReceive;
if (download.Progress.HasRestarted)
{ /* Download restarted */ };
if (download.Progress.HasResponseChanged) // We've received new response headers from the server.
Debug.WriteLine(" - Response updated; Header count: " + download.GetResponseInformation().Headers.Count);
}

二、HttpClient简单应用

  要使用HttpClicet,需对http协议要有一定的了解才行,可以去找些资料了解Http协议(我是从这篇文章http://www.cnblogs.com/zhili/archive/2012/08/18/HTTP.html初步了解了Http)。过程图可以参考下图:

1、利用Http简单地获取文本例子

try
{
// Create the HttpClient
HttpClient httpClient = new HttpClient(); // Optionally, define HTTP headers
httpClient.DefaultRequestHeaders.Accept.TryParseAdd("application/json");//表示客户端可接收json类型的文本 // Make the call
string responseText = await httpClient.GetStringAsync(
new Uri("http://services.odata.org/Northwind/Northwind.svc/Suppliers"));
}
catch (Exception ex)
{
...
}

ps:这里使用的httpclient来自命名空间Windows.Web.Http,而不是System.Net.Http。(两者有区别)

2、获取http响应

try
{
var client = new HttpClient();
var uri = new Uri(" http://example.com/customers/1");
var response = await client.GetAsync(uri);//GetAsync代替GetstringAsync,可以获得更多内容 // code and results
var statusCode = response.StatusCode;
// EnsureSuccessStatusCode throws exception if not HTTP 200
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
...
}

3、写http请求的头部

var client = new HttpClient();
// set some headers
var headers = client.DefaultRequestHeaders;//获取头部
headers.Referer = new Uri("http://contoso.com");//表示的是上一连接的url,如跳转到本页面的上一页面url
var ok = headers.UserAgent.TryParseAdd("testprogram/1.0");//表示客户端软件类型 // make the request
var response = await client.GetAsync(uri);
// get response content length
var length = response.Content.Headers.ContentLength.Value;
byte[] buffer = new byte[length];

我们可以对请求头部进行更多的操作,如下图:

3、对请求行(方法)操作

var client = new HttpClient();
// we're sending a delete request
var request = new HttpRequestMessage(HttpMethod.Delete, uri);//http方法Delette
// we don't expect a response, but we'll snag it anyway
var response = await client.SendRequestAsync(request);

http请求方法还有Delete,Get,Head,Options,Patch,Post,Put等,具体描述可以参考http://www.cnblogs.com/zhili/archive/2012/08/18/HTTP.html

4、设置及获取cookies

(1)设置cookies

var uri = new Uri("http://example.com/customers/1");

try
{
var baseFilter = new HttpBaseProtocolFilter();
var cookieManager = baseFilter.CookieManager; var cookie = new HttpCookie("favoriteColor", ".example.com", "/")
{ Value = "purple"}; cookieManager.SetCookie(cookie); var client = new HttpClient(baseFilter);
await client.PostAsync(uri, new HttpStringContent("Pete"));
}
catch (Exception ex) { ... }

(2)获取cookies

var baseFilter = new HttpBaseProtocolFilter();
var cookieManager = baseFilter.CookieManager; var client = new HttpClient(baseFilter); var cookies = cookieManager.GetCookies(uri); // display cookies
foreach (var cookie in cookies)
{
CookieList.Text += cookie.Name + " = " + cookie.Value + "\n";
}

5、使用HttpBaseProtocolFilter

HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
// When AutomaticDecompression is true (the default), the Accept-Encoding header is added
// to the headers and set to allow gzip and compress
filter.AutomaticDecompression = true; PasswordCredential creds = new PasswordCredential("JumpStart", userName, password);
filter.ServerCredential = creds;
filter.ProxyCredential = creds; // Create the HttpClient
HttpClient httpClient = new HttpClient(filter);

三、使用httpclient完整的demo

  demo实现从网站一图片下载到手机中并显示在页面上。

1、Page的xaml主要代码如下:

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border x:Name="ImageBorder" Grid.Row="1">
<Image x:Name="MainImage"/>
</Border>
<Button x:Name="DownloadButton" Content="Get Image" HorizontalAlignment="Left" Margin="142,47,0,0" Grid.Row="2" VerticalAlignment="Top" Click="DownloadButton_Click"/>
</Grid>

2、Page的C#主要代码如下:

 private async void DownloadButton_Click(object sender, RoutedEventArgs e)
{
Size downloadSize = new Size(
(int)(ImageBorder.ActualWidth * DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel),
(int)(ImageBorder.ActualHeight * DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel));
//Size downloadSize = new Size(744, 360);
await DownloadAndScale("bg-homepage.jpg", "http://www.qnwfan.com/images/bg-homepage.jpg", downloadSize); StorageFolder resultsFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Results");//进入图片存放的文件夹
StorageFile file = await resultsFolder.GetFileAsync("bg-homepage.jpg");//选取对应图片文件 using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) //取图片放到MainImage
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
MainImage.Source = bitmapImage;
}
} private async Task DownloadAndScale(string outfileName, string downloadUriString, Size scaleSize)
{
Uri downLoadingUri = new Uri(downloadUriString);
HttpClient client = new HttpClient();//创建一个http客户端
using (var response = await client.GetAsync(downLoadingUri))//获取响应
{
var buffer = await response.Content.ReadAsBufferAsync();//缓存响应数据内容
var memoryStream = new InMemoryRandomAccessStream();//创建一个数据流
await memoryStream.WriteAsync(buffer);//把buffer缓存区里的数据写入数据流中
await memoryStream.FlushAsync();//数据流刷新
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memoryStream);//数据流解码成图片
var bt = new Windows.Graphics.Imaging.BitmapTransform();//设置图片大小
bt.ScaledWidth = (uint)scaleSize.Width;
bt.ScaledHeight = (uint)scaleSize.Height;
var pixelProvider = await decoder.GetPixelDataAsync(
decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, bt,
ExifOrientationMode.IgnoreExifOrientation, ColorManagementMode.ColorManageToSRgb);//使已初步解码后的图片进一步通过一些设置(设置图片帧格式,图片方向,图片大小等)还原成适合在屏幕显示的图片,成为像素提供源 // 既然我们有了像素数据,那么可以把数据储存在文件夹中
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var resultsFolder = await localFolder.CreateFolderAsync("Results", CreationCollisionOption.OpenIfExists);
var scaledFile = await resultsFolder.CreateFileAsync(outfileName, CreationCollisionOption.ReplaceExisting);
using (var scaledFileStream = await scaledFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(
Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, scaledFileStream);//
var pixels = pixelProvider.DetachPixelData();//获取像素数据
encoder.SetPixelData(
decoder.BitmapPixelFormat,
decoder.BitmapAlphaMode,
(uint)scaleSize.Width,
(uint)scaleSize.Height,
decoder.DpiX,
decoder.DpiY,
pixels
);//设置有关帧的像素数据
await encoder.FlushAsync();//刷新
}

3、实现效果图

点击GetImage前后

WP8.1 Study17:网络之后台下载/上传及HttpClient的更多相关文章

  1. Android okHttp网络请求之文件上传下载

    前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...

  2. android+nutz后台如何上传和下载图片

    android+nutz后台如何上传和下载图片  发布于 588天前  作者 yummy222  428 次浏览  复制  上一个帖子  下一个帖子  标签: 无 最近在做一个基于android的ap ...

  3. ecshop 后台批量上传商品 完整上传

    ecshop 后台批量上传商品,之所以无法上传,是因为后台上传php文件方法中没有导入商品原图路径 将ecshop根目录中的admin/goods_batch.php文件全部修改为 <?php ...

  4. 织梦DEDE网站后台如何上传附件

    如题,织梦DEDE网站后台如何上传附件?今天本人遇到这样的问题,在网站后台里点击一番后,成功上传了一个pdf文件和doc文件,特来分享经验. 工具/原料 织梦dede网站 doc文件 方法/步骤 1 ...

  5. AFNetworking网络请求与图片上传工具(POST)

    AFNetworking网络请求与图片上传工具(POST) .h文件 #import <Foundation/Foundation.h> /** 成功Block */ typedef vo ...

  6. iOS开发网络篇—文件的上传

    iOS开发网络篇—文件的上传 说明:文件上传使用的时POST请求,通常把要上传的数据保存在请求体中.本文介绍如何不借助第三方框架实现iOS开发中得文件上传. 由于过程较为复杂,因此本文只贴出部分关键代 ...

  7. phpcms v9升级后台无法上传缩略图的原因分析

    phpcms V9 是目前国内使用人数最多的一款开源免费的CMS系统,正是由于他的免费性,开源性,以及其自身的功能性比较强大,所以倍受许多站长朋友们的亲来,以及许多的公司的喜欢.phpcms也为了完善 ...

  8. https 协议下服务器根据网络地址下载上传文件问题

    https 协议下服务器根据网络地址下载上传文件遇到(PKIX:unable to find valid certification path to requested target 的问题) 使用h ...

  9. git下载/上传文件提示:git did not exit cleanly

    问题:git操作下载/上传文件,提示信息如下 TortoiseGit-git did not exit cleanly (exit code 1) TortoiseGit-git did not ex ...

随机推荐

  1. python学习笔记系列----(二)控制流

    实际开始看这一章节的时候,觉得都不想看了,因为每种语言都会有控制流,感觉好像我不看就会了似的.快速预览的时候,发现了原来还包含了对函数定义的一些描述,重点讲了3种函数形参的定义方法,章节的最后讲述了P ...

  2. Linq join

    MXS&Vincene  ─╄OvЁ  &0000022─╄OvЁ  MXS&Vincene MXS&Vincene  ─╄OvЁ:今天很残酷,明天更残酷,后天很美好, ...

  3. Cordova for Android(Windows)环境配置

    PS:注意事项 一些坑在此声明: 1.安装Eclipse后,记得设置各项编码格式为utf-8 请移步:http://www.blogjava.net/xiaomage234/archive/2014/ ...

  4. Linux C Programing - Arguments(2)

    #include <iostream> #include <stdlib.h> #include <stdio.h> //printf #include <u ...

  5. 【转】 #1451 - Cannot delete or update a parent row: a foreign key constraint fails 问题的解决办法

    转载地址:http://blog.csdn.net/donglynn/article/details/17056099 错误 SQL 查询: DELETE FROM `zmax_lang` WHERE ...

  6. JS事件整理

    onclick 鼠标点击事件 ondblclick 鼠标双击事件 onmouseover 鼠标移入事件 onmouseout 鼠标移出事件 onmousedown 鼠标按下事件 onmousemove ...

  7. 【20160924】GOCVHelper 图像处理部分(1)

    增强后的图像需要通过图像处理获得定量的值.在实际程序设计过程中,轮廓很多时候都是重要的分析变量.参考Halcon的相关函数,我增强了Opencv在这块的相关功能.      //寻找最大的轮廓     ...

  8. SourceTree 免登录跳过初始设置

    SourceTree 安装之后需要使用账号登陆以授权,以前是可以不登陆的,但是现在是强制登陆. 虽然是免费授权,但是碰上不可抗力因素,登陆不是很方便,这里记录一下跳过这个初始化的步骤. 安装之后,转到 ...

  9. Spark 1.1.0 安装测试 (分布式 Yarn-cluster模式)

    Spark版本:spark-1.1.0-bin-hadoop2.4 (下载:http://spark.apache.org/downloads.html) 服务器环境的情况,请参考上篇博文 hbase ...

  10. 读书笔记 1 of Statistics :Moments and Moment Generating Functions (c.f. Statistical Inference by George Casella and Roger L. Berger)

    Part 1: Moments Definition 1 For each integer $n$, the nth moment of $X$, $\mu_n^{'}$ is \[\mu_{n}^{ ...