Web请求CSharp

时间:2019-04-03 13:14:14

标签: c# web webclient

我有一个C#代码,该代码使用来自外部站点的Web服务数据。它正在工作并在我的页面上显示天气数据,但现在它抛出“ WebClient请求期间发生异常”错误。我试图对此进行研究,但没有运气。

protected void GetWeatherInfo(string url)
    {

        string url1 = string.Format(url);
        using (WebClient client = new WebClient())
        {
            WebProxy proxyObj = new WebProxy(url1);

            proxyObj.Credentials = CredentialCache.DefaultCredentials;


            client.Proxy = proxyObj;
            try
            {
                string json = client.DownloadString(url1);

                WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize<WeatherInfo>(json);
                lblCity_Country.Text = weatherInfo.city.name + "," + weatherInfo.city.country;
                imgCountryFlag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.city.country.ToLower());
                lblDescription.Text = weatherInfo.list[0].weather[0].description;
                imgWeatherIcon.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.list[0].weather[0].icon);
                lblTempMin.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.min, 1));
                lblTempMax.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.max, 1));
                lblTempDay.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.day, 1));
                lblTempNight.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.night, 1));
                lblHumidity.Text = weatherInfo.list[0].humidity.ToString();
                tblWeather.Visible = true;
            }
            catch (Exception ex)
            {
                string excep = ex.Message;
            }

        }
    }

0 个答案:

没有答案