前文讲到WP8中使用Async执行HTTP请求,用了微软提供的扩展。下面提供了一种方法,自己实现HttpWebRequest的扩展。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55class="csharp keyword">namespace
HttpExtensions
{
public
static
class
WebRequestExtensions
{
public
async
static
Task<WebResponse> GetResponseAsync(
this
HttpWebRequest request)
{
var
tcs =
new
TaskCompletionSource<WebResponse>();
try
{
request.BeginGetResponse((ar) =>
{
var
response = request.EndGetResponse(ar);
tcs.SetResult(response);
},
null
);
}
catch
(WebException we)
{
tcs.SetException(we);
}
return
await tcs.Task;
}
public
async
static
Task<WebResponse> GetResponseAsync(
this
HttpWebRequest request,
string
post)
{
var
tcs =
new
TaskCompletionSource<WebResponse>();
try
{
request.BeginGetRequestStream((arReq) =>
{
var
stream = request.EndGetRequestStream(arReq);
using
(StreamWriter writer =
new
StreamWriter(stream))
{
writer.Write(post);
writer.Flush();
}
request.BeginGetResponse((ar) =>
{
var
response = request.EndGetResponse(ar);
tcs.SetResult(response);
},
null
);
},
null
);
}
catch
(WebException we)
{
tcs.SetException(we);
}
return
await tcs.Task;
}
}
}
随后就可以使用 await HttpWebRequest.GetResponseAsync() 轻松使用http请求了。
原文http://blog.liubaicai.com/?p=280