我在 VS Express for WP 2012 中面对 HttpWebRequest 的异步,我的目标是 WP 7.1。
我想编写一个返回 URL 结果的方法,如下所示:
public static string GetContentByPass(string link)
{
string result = "";
var request = (HttpWebRequest)WebRequest.Create(
new Uri(link));
request.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse) httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
{
result = response;
}));
}
}, request);
return result;
}
像这样使用:
result = Util.GetContentByPass("http://google.com");
但结果总是空的。
任何的想法?
谢谢 :-)
编辑
这是我的解决方案,希望它能帮助需要的人:-)
public static string GetContentFromURL(string url)
{
var task = GetResult(url);
return task.Result;
}
private static Task<string> GetResult(string url)
{
url = url.Replace("http://","");
url = "http://" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
Task<WebResponse> task = Task.Factory.FromAsync(
request.BeginGetResponse, asyncResult => request.EndGetResponse(asyncResult), (object)null
);
return task.ContinueWith(t => ReadStreamFromResponse(t.Result));
}
private static string ReadStreamFromResponse(WebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader sr = new StreamReader(responseStream))
{
//Need to return this response
string strContent = sr.ReadToEnd();
return strContent;
}
}