询问者
关于Windows Phone开发中使用WebClient获取网页源码的问题

问题
-
public static string GetHTML(string url)
{
Uri u = new Uri(url);
string strHTML = string.Empty;
wc.OpenReadAsync(u);
wc.OpenReadCompleted+=new OpenReadCompletedEventHandler((object obj,OpenReadCompletedEventArgs e)=>{
StreamReader sr = new StreamReader (e.Result);
strHTML = sr.ReadToEnd();
sr.Close();
e.Result.Close();
});
while (true)
if (strHTML != String.Empty)
return strHTML;
}如上是我的代码,作用是获取包含url源码的字符串 本代码在WinForm中测试成功,于是我把拿到了WP程序中。
但是测试的时候始终不能触发完成事件,strHTML始终为空,于是方法不能完成(已确认URL有效)
这是怎么回事(WP8模拟器已联网),或者是否有其他方法?(DownloadStringAsync方法同样不能用)
全部回复
-
你好,
从MSDN的Help上来看,
You cannot call the OpenReadAsync method again on the same WebClient object, until the first download operation is completed. Doing this causes an exception.
是否把WebClient webClient = new WebClient()放在同一个函数中为好。
如:
private void DoWebClient()
{
WebClient webClient = new WebClient();
webClient.OpenReadAsync(new Uri("http://www.cnblogs.com/linzheng"));//在不阻止调用线程的情况下,从资源返回数据
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);//异步操作完成时发生
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (StreamReader reader = new StreamReader(e.Result))
{
string contents = reader.ReadToEnd();
int begin = contents.ToString().IndexOf("<title>");
int end = contents.ToString().IndexOf("</title>");
string note = contents.Substring(contents.ToString().IndexOf("摘要"), 300);
webClientTextBlock.Text = contents.ToString().Substring(begin+7, end - begin-7);
textBox1.Text = note;
}
}Keep Fighting