原文 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. SQL Server 加密层级

    ---------------------------------------------------------------------------------------------------- ...

  2. Oracle EBS-SQL (WIP-13):检查任务组件未选MRP净值.sql

    select WE.WIP_ENTITY_NAME                                              任务号,         MFG_LOOKUPS_WJS. ...

  3. 如何在同一系统里同时启动多个Tomcat

    需要在同一系统里启动多个tomcat,应该怎么处理? tomcat是个服务程序,需要占用几个通讯端口,所以默认情况是不能启动多个tomcat,如果要启动多个tomcat,需要修改配置文件,通过在配置文 ...

  4. javascript预加载和延迟加载

    延迟加载javascript,也就是页面加载完成之后再加载javascript,也叫on demand(按需)加载,一般有一下几个方法: What can your tired old page, o ...

  5. python手记(51)

    python通过声音将文件内容隐藏,实现原理是将文件的内容分别插入到声音文件的不同位置中做为当次采样的数据,目前是对英文文本文档加解密 #!/usr/bin/env python # -*- codi ...

  6. (译)iPhone: 用公开API创建带小数点的数字键盘 (OS 3.0, OS 4.0)

    (译)iPhone: 用公开API创建带小数点的数字键盘 (OS 3.0, OS 4.0) 更新:ios4.1现在已经将这个做到SDK了.你可以设置键盘类型为UIKeyboardTypeDecimal ...

  7. Codeforces 286E

    #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> # ...

  8. linux GUI程序开发

    1,C++ OOP中 class与C 面向过程开发中struct非常相似

  9. How to convert string to wstring?

    How to convert string to wstring? - Codejie's C++ Space - C++博客     How to convert string to wstring ...

  10. ByteBuffer用法总结

    转自:http://blog.csdn.net/mars5337/article/details/6576417 在NIO中,数据的读写操作始终是与缓冲区相关联的.读取时信道(SocketChanne ...