C# 如何异步检索多个网站?
使用silverlight Windows Phone 8.1项目 我正在尝试从网站加载数据。不过,我必须首先在该站点进行身份验证。 因此,我在网站上发布了一篇文章,使用了来自的CookieAwareWebClient的稍加修改的版本 现在,我让一个WebClient发送一个带有C# 如何异步检索多个网站?,c#,cookies,asynchronous,webclient,windows-phone-8.1,C#,Cookies,Asynchronous,Webclient,Windows Phone 8.1,使用silverlight Windows Phone 8.1项目 我正在尝试从网站加载数据。不过,我必须首先在该站点进行身份验证。 因此,我在网站上发布了一篇文章,使用了来自的CookieAwareWebClient的稍加修改的版本 现在,我让一个WebClient发送一个带有用户名和密码的POST,继续获取我的站点异步,并在我的下载StringCompleted EventHandler中处理站点数据。 到现在为止,一直都还不错。 现在我想在这一点上扩展,并获得多个网站。 我没有一次就把它们
用户名和密码的POST
,继续获取我的站点异步,并在我的下载StringCompleted EventHandler
中处理站点数据。
到现在为止,一直都还不错。
现在我想在这一点上扩展,并获得多个网站。
我没有一次就把它们全部拿到手,事实上最好是一个接一个地把它们拿到手
但我不知道该怎么做
到目前为止我的代码:
using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Windows.Web.Http;
using Microsoft.Phone.Shell;
using StackOverflowApp.Resources;
namespace StackOverflowApp
{
public partial class MainPage
{
private const string URL_DATES = @"/subsite/dates";
private const string URL_RESULTS = @"/subsite/results";
private readonly ApplicationBarIconButton btn;
private int runningOps = 0;
//Regex's to parse websites
private readonly Regex regexDates = new Regex(AppResources.regexDates);
private readonly Regex regexResults = new Regex(AppResources.regexResults);
private readonly CookieAwareWebClient client = new CookieAwareWebClient();
private int status;
// Konstruktor
public MainPage()
{
InitializeComponent();
btn = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]);
// = application/x-www-form-urlencoded
client.Headers[HttpRequestHeader.ContentType] = AppResources.ContentType;
client.UploadStringCompleted += UploadStringCompleted;
client.DownloadStringCompleted += DownloadStringCompleted;
}
private void GetSite()
{
const string POST_STRING = "name={0}&password={1}";
var settings = new AppSettings();
if (settings.UsernameSetting.Length < 3 || settings.PasswordSetting.Length < 3)
{
MessageBox.Show(
(settings.UsernameSetting.Length < 3
? "Bitte geben Sie in den Einstellungen einen Benutzernamen ein\r\n" : string.Empty)
+
(settings.PasswordSetting.Length < 3
? "Bitte geben Sie in den Einstellungen ein Kennwort ein\r\n" : string.Empty)
);
return;
}
LoadingBar.IsEnabled = true;
LoadingBar.Visibility = Visibility.Visible;
client.UploadStringAsync(
new Uri(AppResources.BaseAddress + "subsite/login"),
"POST",
string.Format(POST_STRING, settings.UsernameSetting, settings.PasswordSetting));
}
private void LoadDates()
{
status = 0; //Termine
runningOps++;
client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_DATES));
}
private void LoadResults()
{
status = 1; //Ergebnisse
runningOps++;
client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_RESULTS));
}
private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
runningOps--;
if (runningOps == 0)
{
//alle Operationen sind fertig
LoadingBar.IsEnabled = false;
LoadingBar.Visibility = Visibility.Collapsed;
btn.IsEnabled = true;
}
if (e.Cancelled || e.Error != null) return;
//Antwort erhalten
var source = e.Result.Replace("\r", "").Replace("\n", "");
switch (status)
{
case 0: //Termine geladen
foreach (Match match in regexDates.Matches(source))
{
var tb = new TextBlock();
var g = match.Groups;
tb.Text = string.Format(
"{1} {2} {3}{0}{4} {5}{0}{6}",
Environment.NewLine,
g[1].Value,
g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
g[5].Value,
g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
(
g[7].Captures.Count > 0
? g[7].Value
: string.Empty
)
+
(
g[8].Captures.Count > 0
? g[8].Value != g[4].Value
? g[8].Value + " != " + g[4].Value
: g[8].Value
: g[4].Captures.Count > 0
? g[4].Value
: string.Empty
)
);
DatesPanel.Children.Add(tb);
}
break;
case 1: //Ergebnisse geladen
foreach (Match match in regexResults.Matches(source))
{
var tb = new TextBlock();
var g = match.Groups;
tb.Text = string.Format(
"{1} {2} {3}{0}{4} {5}{0}{6}",
Environment.NewLine,
g[1].Value,
g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
g[5].Value,
g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
(
g[7].Captures.Count > 0
? g[7].Value
: string.Empty
)
+
(
g[8].Captures.Count > 0
? g[8].Value != g[4].Value
? g[8].Value + " != " + g[4].Value
: g[8].Value
: g[4].Captures.Count > 0
? g[4].Value
: string.Empty
)
);
ResultsPanel.Children.Add(tb);
}
break;
default:
return;
}
}
void UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
//Login completed
LoadDates();
//THIS WOULD YIELD AN ERROR FROM THE WEBCLIENT SAYING IT ISNT SUPPORTING MULTIPLE ASYNC ACTIONS
//LoadResults();
}
private async void ClickOnRefresh(object sender, EventArgs e)
{
var isUp = await IsUp();
if (isUp)
GetSite();
else
MessageBox.Show("Die Seite ist down! :(");
}
private void ClickOnSettings(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
}
private async Task<bool> IsUp()
{
btn.IsEnabled = false;
const string ISUPMELINK = "http://www.isup.me/{0}";
var data = await RequestData(string.Format(ISUPMELINK, AppResources.BaseAddress.Replace("https://", string.Empty)));
var isUp = !data.Contains("It's not just you!");
btn.IsEnabled = true;
return isUp;
}
private async void ClickOnTestConnection(object sender, EventArgs e)
{
var isUp = await IsUp();
MessageBox.Show(string.Format("Die Seite ist {0}! :{1}", isUp ? "up" : "down", isUp ? ")" : "("));
}
private static async Task<string> RequestData(string url)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(new Uri(url));
}
}
}
使用系统;
Net系统;
使用System.Text.RegularExpressions;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用Windows.Web.Http;
使用Microsoft.Phone.Shell;
使用StackOverflowApp.Resources;
命名空间StackOverflowApp
{
公共部分类主页
{
私有常量字符串URL_DATES=@“/子网站/日期”;
私有常量字符串URL_RESULTS=@“/子网站/结果”;
专用只读应用程序BariconButton btn;
私有int runningOps=0;
//正则表达式解析网站
private readonly Regex regexDates=新的Regex(AppResources.regexDates);
private readonly Regex regexResults=new Regex(AppResources.regexResults);
私有只读CookieAwareWebClient=新CookieAwareWebClient();
私人身份;
//康斯特鲁克托
公共主页()
{
初始化组件();
btn=((ApplicationBarIconButton)ApplicationBar.Buttons[0]);
//=应用程序/x-www-form-urlencoded
client.Headers[HttpRequestHeader.ContentType]=AppResources.ContentType;
client.UploadStringCompleted+=UploadStringCompleted;
client.DownloadStringCompleted+=DownloadStringCompleted;
}
私有void GetSite()
{
conststring POST_string=“name={0}&password={1}”;
var settings=新的AppSettings();
if(settings.usernameseting.Length<3 | | settings.PasswordSetting.Length<3)
{
MessageBox.Show(
(settings.usernameseting.Length<3
?“您在安装过程中被咬了一口\r\n”:string.Empty)
+
(settings.PasswordSetting.Length<3
?“您在肯尼沃特的花园里吃了一顿饭\r\n”:string.Empty)
);
返回;
}
LoadingBar.IsEnabled=true;
LoadingBar.Visibility=可见性.Visibility;
client.UploadStringAsync(
新Uri(AppResources.BaseAddress+“子网站/登录”),
“职位”,
Format(POST_string,settings.usernameseting,settings.PasswordSetting));
}
私有void LoadDates()
{
状态=0;//终止
runningOps++;
client.DownloadStringAsync(新Uri(AppResources.BaseAddress+URL_DATES));
}
私有void LoadResults()
{
status=1;//Ergebnisse
runningOps++;
DownloadStringAsync(新Uri(AppResources.BaseAddress+URL_结果));
}
私有void DownloadStringCompleted已完成(对象发送方,DownloadStringCompletedEventArgs e)
{
运行操作--;
如果(运行操作==0)
{
//所有的操作都在进行中
LoadingBar.IsEnabled=false;
LoadingBar.Visibility=Visibility.collazed;
btn.IsEnabled=true;
}
如果(e.取消| | e.错误!=null)返回;
//益母草
var source=e.Result.Replace(“\r”,”).Replace(“\n”,”);
开关(状态)
{
案例0://Termine geladen
foreach(regexDates.Matches中的匹配(源))
{
var tb=新的TextBlock();
var g=匹配组;
tb.Text=string.Format(
"{1} {2} {3}{0}{4} {5}{0}{6}",
环境,新线,
g[1].值,
g[2]。Captures.Count>0?g[2]。值:string.Empty,
g[3]。Captures.Count>0?”-“+g[3]。值:string.Empty,
g[5].值,
g[6]。Captures.Count>0?“bei”+g[6]。值:string.Empty,
(
g[7].Captures.Count>0
?g[7]。数值
:string.Empty
)
+
(
g[8].Captures.Count>0
?g[8]。值!=g[4]。值
?g[8]。值+“!=”+g[4]。值
:g[8]。值
:g[4].捕获数.Count>0
?g[4]。数值
:string.Empty
)
);
DatesPanel.Children.Add(tb);
}
打破
案例1://Ergebnisse geladen
foreach(regexResults.Matches中的匹配(源))
{
var tb=新的TextBlock();
var g=m
using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Windows.Web.Http;
using Microsoft.Phone.Shell;
using StackOverflowApp.Resources;
namespace StackOverflowApp
{
public partial class MainPage
{
private const string URL_DATES = @"/subsite/dates";
private const string URL_RESULTS = @"/subsite/results";
private readonly ApplicationBarIconButton btn;
private int runningOps = 0;
//Regex's to parse websites
private readonly Regex regexDates = new Regex(AppResources.regexDates);
private readonly Regex regexResults = new Regex(AppResources.regexResults);
private readonly CookieAwareWebClient client = new CookieAwareWebClient();
private int status;
// Konstruktor
public MainPage()
{
InitializeComponent();
btn = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]);
// = application/x-www-form-urlencoded
client.Headers[HttpRequestHeader.ContentType] = AppResources.ContentType;
client.UploadStringCompleted += UploadStringCompleted;
client.DownloadStringCompleted += DownloadStringCompleted;
}
private void GetSite()
{
const string POST_STRING = "name={0}&password={1}";
var settings = new AppSettings();
if (settings.UsernameSetting.Length < 3 || settings.PasswordSetting.Length < 3)
{
MessageBox.Show(
(settings.UsernameSetting.Length < 3
? "Bitte geben Sie in den Einstellungen einen Benutzernamen ein\r\n" : string.Empty)
+
(settings.PasswordSetting.Length < 3
? "Bitte geben Sie in den Einstellungen ein Kennwort ein\r\n" : string.Empty)
);
return;
}
LoadingBar.IsEnabled = true;
LoadingBar.Visibility = Visibility.Visible;
client.UploadStringAsync(
new Uri(AppResources.BaseAddress + "subsite/login"),
"POST",
string.Format(POST_STRING, settings.UsernameSetting, settings.PasswordSetting));
}
private void LoadDates()
{
status = 0; //Termine
runningOps++;
client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_DATES));
}
private void LoadResults()
{
status = 1; //Ergebnisse
runningOps++;
client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_RESULTS));
}
private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
runningOps--;
if (runningOps == 0)
{
//alle Operationen sind fertig
LoadingBar.IsEnabled = false;
LoadingBar.Visibility = Visibility.Collapsed;
btn.IsEnabled = true;
}
if (e.Cancelled || e.Error != null) return;
//Antwort erhalten
var source = e.Result.Replace("\r", "").Replace("\n", "");
switch (status)
{
case 0: //Termine geladen
foreach (Match match in regexDates.Matches(source))
{
var tb = new TextBlock();
var g = match.Groups;
tb.Text = string.Format(
"{1} {2} {3}{0}{4} {5}{0}{6}",
Environment.NewLine,
g[1].Value,
g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
g[5].Value,
g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
(
g[7].Captures.Count > 0
? g[7].Value
: string.Empty
)
+
(
g[8].Captures.Count > 0
? g[8].Value != g[4].Value
? g[8].Value + " != " + g[4].Value
: g[8].Value
: g[4].Captures.Count > 0
? g[4].Value
: string.Empty
)
);
DatesPanel.Children.Add(tb);
}
break;
case 1: //Ergebnisse geladen
foreach (Match match in regexResults.Matches(source))
{
var tb = new TextBlock();
var g = match.Groups;
tb.Text = string.Format(
"{1} {2} {3}{0}{4} {5}{0}{6}",
Environment.NewLine,
g[1].Value,
g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
g[5].Value,
g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
(
g[7].Captures.Count > 0
? g[7].Value
: string.Empty
)
+
(
g[8].Captures.Count > 0
? g[8].Value != g[4].Value
? g[8].Value + " != " + g[4].Value
: g[8].Value
: g[4].Captures.Count > 0
? g[4].Value
: string.Empty
)
);
ResultsPanel.Children.Add(tb);
}
break;
default:
return;
}
}
void UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
//Login completed
LoadDates();
//THIS WOULD YIELD AN ERROR FROM THE WEBCLIENT SAYING IT ISNT SUPPORTING MULTIPLE ASYNC ACTIONS
//LoadResults();
}
private async void ClickOnRefresh(object sender, EventArgs e)
{
var isUp = await IsUp();
if (isUp)
GetSite();
else
MessageBox.Show("Die Seite ist down! :(");
}
private void ClickOnSettings(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
}
private async Task<bool> IsUp()
{
btn.IsEnabled = false;
const string ISUPMELINK = "http://www.isup.me/{0}";
var data = await RequestData(string.Format(ISUPMELINK, AppResources.BaseAddress.Replace("https://", string.Empty)));
var isUp = !data.Contains("It's not just you!");
btn.IsEnabled = true;
return isUp;
}
private async void ClickOnTestConnection(object sender, EventArgs e)
{
var isUp = await IsUp();
MessageBox.Show(string.Format("Die Seite ist {0}! :{1}", isUp ? "up" : "down", isUp ? ")" : "("));
}
private static async Task<string> RequestData(string url)
{
using (var httpClient = new HttpClient())
return await httpClient.GetStringAsync(new Uri(url));
}
}
}