原文 http://www.cnblogs.com/java-koma/archive/2013/05/22/3093309.html

1,HttpClient

Win 8提供了System.Net.Http.HttpClient类进行常用的http网络请求,HttpClient提供了以下构造函数。

		// 摘要:
// 初始化 System.Net.Http.HttpClient 类的新实例。
public HttpClient();
//
// 摘要:
// 用特定的处理程序初始化 System.Net.Http.HttpClient 类的新实例。
//
// 参数:
// handler:
// 用于发送请求的使用的 HTTP 处理程序堆栈。
public HttpClient(HttpMessageHandler handler);
//
// 摘要:
// 用特定的处理程序初始化 System.Net.Http.HttpClient 类的新实例。
//
// 参数:
// handler:
// System.Net.Http.HttpMessageHandler 负责处理 HTTP 响应消息。
//
// disposeHandler:
// 如果内部处理程序应由 Dispose () 处理,则为 true;如果您希望重用内部处理程序,则为 false。
public HttpClient(HttpMessageHandler handler, bool disposeHandler);

第2个构造函数常用来处理在请求前添加header(如:Cookie),响应时解析header。

下面使用HttpClient处理POST/GET提交:

#1. 让我们先来定义好key-value类型的参数,用于提交。

	public class Parameter
{
public string key { get; set; }
public string value { get; set; } public Parameter() { }
public Parameter(string key, string value)
{
this.key = key;
this.value = value;
}
}

#2. POST/GET:

		private static async Task<string> doRequest<T>(string url, List<Parameter> paramList, bool isPost)
{
System.Net.Http.HttpClient httpClient = null;
try
{
httpClient = new System.Net.Http.HttpClient();
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
HttpResponseMessage response = null;
// POST
if (isPost)
{
MultipartFormDataContent form = getPostForm(paramList);
response = await httpClient.PostAsync(new Uri(url), form);
}
// GET
else
{
url = generateGetUrl(url, paramList);
response = await httpClient.GetAsync(new Uri(url));
}
return await response.Content.ReadAsStringAsync();
}
catch (Exception) { }
finally
{
if (httpClient != null)
{
httpClient.Dispose();
httpClient = null;
}
}
return null;
}
private static string generateGetUrl(string url, List<Parameter> paramList)
{
if(paramList == null || paramList.Count <= 0)
{
return url;
}
StringBuilder sb = new StringBuilder();
foreach (Parameter item in this.ParamList)
{
if (item == null || string.IsNullOrWhiteSpace(item.key) || string.IsNullOrWhiteSpace(item.value))
{
continue;
}
if (sb.Length > 0)
{
sb.Append("&");
}
sb.Append(string.Format("{0}={1}", item.key, System.Net.WebUtility.UrlEncode(item.value)));
}
return url + (url.IndexOf("?") == -1 ? "?" : "&") + sb.ToString();
} private static MultipartFormDataContent getPostForm(List<Parameter> paramList)
{
MultipartFormDataContent form = new MultipartFormDataContent();
if (paramList != null)
{
foreach (var param in paramList)
{
if (!string.IsNullOrWhiteSpace(param.key))
{
form.Add(new StringContent(param.value, UTF8Encoding.UTF8), param.key);
}
}
}
return form;
}

#3. 处理Cookie,

通常情况下我们需要保持client与server之间的session,server端是通过cookie来识别一个client与另外一个client的。

我们使用上面HttpClient的第2个构造函数,通过MessageProcessingHandler和CookieContainer来每次请求前,把cookie添加到request的header中。

	public class CookieHandler : MessageProcessingHandler
{
static CookieHandler()
{
CookieContainer = new CookieContainer();
} public static CookieContainer CookieContainer
{
get;
set;
} public CookieHandler() : base(new CookieHttpClientHandler())
{
} protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
return request;
} protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, System.Threading.CancellationToken cancellationToken)
{
Uri httpsUri = new Uri("https://" + response.RequestMessage.RequestUri.Host); var cookieCollection = CookieContainer.GetCookies(httpsUri);
foreach (Cookie cookie in cookieCollection)
{
cookie.Secure = false;
} return response;
}
} class CookieHttpClientHandler : HttpClientHandler
{
public CookieHttpClientHandler()
{
CookieContainer = CookieHandler.CookieContainer;
}
}

使用方式跟前面POST/GET代码唯一不同的是:在构造HttpClient对象时,传入CookieHandler:

var httpClient = new System.Net.Http.HttpClient(new CookieHandler());

2, 文件下载

#1 HttpClient提供了字节流的方式来读取文件,但我测试发现,下载是成功了,但文件经常出现缺少字节的情况。不清楚是怎么回事。

		//
// 摘要:
// 将 GET 请求发送到指定 URI 并在异步操作中以字节数组的形式返回响应正文。
//
// 参数:
// requestUri:
// 请求发送到的 URI。
//
// 返回结果:
// 返回 System.Threading.Tasks.Task<TResult>。 表示异步操作的任务对象。
//
// 异常:
// System.ArgumentNullException:
// requestUri 为 null。
public Task<byte[]> GetByteArrayAsync(string requestUri);
//
// 摘要:
// 将 GET 请求发送到指定 URI 并在异步操作中以字节数组的形式返回响应正文。
//
// 参数:
// requestUri:
// 请求发送到的 URI。
//
// 返回结果:
// 返回 System.Threading.Tasks.Task<TResult>。 表示异步操作的任务对象。
//
// 异常:
// System.ArgumentNullException:
// requestUri 为 null。
public Task<byte[]> GetByteArrayAsync(Uri requestUri);
//
// 摘要:
// 将 GET 请求发送到指定 URI 并在异步操作中以流的形式返回响应正文。
//
// 参数:
// requestUri:
// 请求发送到的 URI。
//
// 返回结果:
// 返回 System.Threading.Tasks.Task<TResult>。 表示异步操作的任务对象。
//
// 异常:
// System.ArgumentNullException:
// requestUri 为 null。
public Task<System.IO.Stream> GetStreamAsync(string requestUri);
//
// 摘要:
// 将 GET 请求发送到指定 URI 并在异步操作中以流的形式返回响应正文。
//
// 参数:
// requestUri:
// 请求发送到的 URI。
//
// 返回结果:
// 返回 System.Threading.Tasks.Task<TResult>。 表示异步操作的任务对象。
//
// 异常:
// System.ArgumentNullException:
// requestUri 为 null。
public Task<System.IO.Stream> GetStreamAsync(Uri requestUri);

#2. BackgroundDownloader

Win 8提供了BackgroundDownloader可以用于在后台下载文件,它也可以调用setRequestHeader向请求中添加header信息 (与上面的CookieHandler结合使用,可以处理那些需要登陆才能下载文件的情况),下面演示了普通的文件下载:

		public async static Task<IAsyncOperation<StorageFile>> DownloadAsync(string url)
{
string fileName = url.Substring(url.LastIndexOf("/") + 1).Trim();
var option = Windows.Storage.CreationCollisionOption.ReplaceExisting;
StorageFile destinationFile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, option);
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(new Uri(url), destinationFile);
await download.StartAsync().AsTask();
ResponseInformation response = download.GetResponseInformation();
if(response.StatusCode == 200)
{
DownloadHelper.addDownloadFileSuccess(fileName);
return DownloadHelper.getDownloadFileAsync(fileName);
}
return null;
}

【Windows 8 Store App】学习三:HTTP的更多相关文章

  1. 【Windows 8 Store App】学习二:ResourceLoader

    原文 http://www.cnblogs.com/java-koma/archive/2013/05/22/3093308.html 在项目开发时,通常有一些资源信息需要存储起来,比如请求的URL, ...

  2. 【Windows 8 Store App】学习:目录

    原文http://www.cnblogs.com/java-koma/archive/2013/05/22/3093302.html 写在前面:我之前从事java开发,对MS的一整套东西还没入门哈,难 ...

  3. 【Windows 8 Store App】学习一:获取设备信息

    原文http://www.cnblogs.com/java-koma/archive/2013/05/22/3093306.html 通常情况下我们需要知道用户设备的一些信息:deviceId, os ...

  4. 01、Windows Store APP 设置页面横竖屏的方法

    在 windows phone store app 中,判断和设置页面横竖屏的方法,与 silverlight 中的 Page 类 不同,不能直接通过 Page.Orientation 进行设置.而是 ...

  5. Windows 8.1 store app 开发笔记

    原文:Windows 8.1 store app 开发笔记 零.简介 一切都要从博彦之星比赛说起.今年比赛的主题是使用Bing API(主要提到的有Bing Map API.Bing Translat ...

  6. Windows store app[Part 3]:认识WinRT的异步机制

    WinRT异步机制的诞生背景 当编写一个触控应用程序时,执行一个耗时函数,并通知UI更新,我们希望所有的交互过程都可以做出快速的反应.流畅的操作感变的十分重要. 在连接外部程序接口获取数据,操作本地数 ...

  7. 在桌面程序上和Metro/Modern/Windows store app的交互(相互打开,配置读取)

    这个标题真是取得我都觉得蛋疼..微软改名狂魔搞得我都不知道要叫哪个好.. 这边记录一下自己的桌面程序跟windows store app交互的过程. 由于某些原因,微软的商店应用的安全沙箱导致很多事情 ...

  8. Windows Store App 过渡动画

    Windows Store App 过渡动画     在开发Windows应用商店应用程序时,如果希望界面元素进入或者离开屏幕时显得自然和流畅,可以为其添加过渡动画.过渡动画能够及时地提示用户屏幕所发 ...

  9. 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期

    [源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...

随机推荐

  1. 开发环境配置--Ubuntu+Qt4+OpenCV(三)

    同系列文章 1. 开发环境配置--Ubuntu+Qt4+OpenCV(一) 2. 开发环境配置--Ubuntu+Qt4+OpenCV(二) 3. 开发环境配置--Ubuntu+Qt4+OpenCV(三 ...

  2. Jquery中bind和live.one,delegate的区别

    Jquery中绑定事件有三种方法:以click事件为例 (1)target.click(function(){}); (2)target.bind("click",function ...

  3. Jsoup小Demo

    Jsoup小Demo public class JsoupUtil { public void parseWangYi() { Document doc = null; try { //eg1:解析百 ...

  4. ContentProvider类的解析

    一.ContentProvider类 1.作用:专门用于不同应用之间进行数据共享的方式. 二.实现方法 1.创建ContenteProvider类 步骤一:继承ContentProvider接口,重写 ...

  5. javascript instanceof

    object instanceof constructor instanceof运算符用来检测constructor.prototype是否存在于参数object的原型链上. 对于instanceof ...

  6. docker 保存更改的镜像:

    <pre name="code" class="ruby">保存更改的镜像: docker:/root# docker commit -m &quo ...

  7. JavaEE Tutorials (23) - 资源适配器和契约

    23.1什么是资源适配器362 23.1.1管理契约363 23.1.2通用工作上下文契约364 23.1.3出站和入站契约36423.2元数据注解36523.3公共客户端接口36623.4对Java ...

  8. 编程内功修炼之数据结构—BTree(三)总结

    BTree必须通过各种编程约束,使得不脱离BTree的本身特性: 1)BTree关键字插入操作:插入过程中,如果节点关键字达到上限,添加分裂约束,从而控制每个节点的关键字数维持在 t-1~2*t-1内 ...

  9. C++游戏编程(一开篇)

    本系列文章由zhmxy555(毛星云)编写,转载请注明出处. http://blog.csdn.net/zhmxy555/article/details/7318264 作者:毛星云    邮箱: h ...

  10. ASP.Net连接SQLServer 连接字符串

    引用命名空间 using System.Data; using System.Data.SqlClient; 连接字符串 // windows 验证方式数据库中存在单一实例 string connec ...