Skip to main content
 首页 » 编程设计

c#之当互联网连接速度慢时 : WebException之The remote server returned an error: NotFound

2024年02月13日34lexus

我在我的应用程序中使用 2 个 WebClient,用于 2 个不同的天气 API。

当我的互联网连接速度很慢时,我从其中一个 API 收到异常。它返回 404 Notfound 错误。

我已经通过禁用我的 WiFi 进行了测试,并将数据连接设置为“2G”。第一个 API 毫无问题地返回数据,但是第二个 API 使我的应用程序崩溃并出现 WebException。

当我再次打开 WiFi 时,它可以正常工作。看起来第二个 API 对慢速连接没有耐心。

有办法解决这个问题吗?我也尝试将 WebClient 更改为 HttpWebRequest,但问题仍然存在。

亲切的问候, 尼尔斯

编辑 我的代码:

    private void GettingTheData() 
    { 
         WebClient Client = new WebClient(); 
         Client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Client _DownloadStringCompleted); 
 
         Client.DownloadStringAsync(new Uri("http://theURI.com")); 
    } 
 
void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
   { 
 
    string result = e.Result.ToString(); 
    // Let's do the cool stuff overhere 
} 

请您参考如下方法:

存在HTTP Client library对于包含超时支持的 WP。 Article关于它。

Windows Phone 8 的一些示例代码:

protected async override void OnNavigatedTo(NavigationEventArgs e) 
{ 
     var httpClient = new HttpClient {Timeout = TimeSpan.FromSeconds(30)}; 
     var responseBodyAsText = await httpClient.GetStringAsync("www.contoso.com"); 
}