网络客户端重试
是否可以重试网络客户端请求?在奇怪的情况下,我的应用程序在尝试连接到 xml web 服务时会抛出错误,但如果我重试,它会正常工作。我希望它在抛出错误之前重试两次,除非有人有更好的解决方案:)
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else
{
MessageBox.Show("Authentication successfull.");
}
}
Is it possible to retry a webclient request? On the odd occasion my application will throw an error when attempting to connect to an xml web service but if I retry, it works OK. I'd like it to retry 2 times before throwing an error unless someone has a better solution :)
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else
{
MessageBox.Show("Authentication successfull.");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果失败,您可以重新发出请求。通过记录重新发出请求的次数,您可以确定何时向用户显示错误。这是对您的代码的快速修改,以演示我的意思。
If you get a failure, you could re-issue the request. By keeping count of the number of times you re-issue the request you can determine when to show the user an error. Here is a quick modification to your code to demonstrate what I mean.
WebClient 没有任何内置的重试功能。
您应该在通知用户问题之前自行构建重试逻辑。
WebClient doesn't have any built in retry functionality.
You should look to build the retry logic yourself before, probably, informing the user of the problem.