2015-04-02 119 views
0

我一直通过访问他们的XML文件从国家气象服务获取天气信息。但截至今天,我不断得到访问被拒绝的错误(403)我的服务器是否被阻止?如果是这样我可以在美国免费获取天气信息?天气API http://www.weather.gov/

我不敢相信我的网络服务只有几个点击就被阻止。以防万一这是我用来测试天气数据的计划任务:

public override async Task ExecuteAsync() 
    { 
     GoogleGeocoder geocoder; 
     //Geocode variables 
     string apiKey = WebConfigurationManager.AppSettings["googleApiKey"]; 

     if (String.IsNullOrEmpty(apiKey)) 
     { 
      geocoder = new GoogleGeocoder(); 
     } 
     else 
     { 
      geocoder = new GoogleGeocoder(apiKey); 
     } 



     string longitude = string.Empty; 

     string latitude = string.Empty; 

     var xdoc = new XDocument(); 

     var project = Project(); 

     //Query for each project and get their longitude and latitude 

     DataTable dataTable = SqlHelper.ExecuteDataset("getAll", "1").Tables[0]; 

     if (dataTable.Rows.Count > 0) { 
      foreach (DataRow dataRow in dataTable.Rows) { 
       Map.DataToObject(dataRow, project); 

       //Find Longitude and latitude based on zipcode or address. 
       IEnumerable<Address> addresses = geocoder.Geocode(project.SiteCity + "," + project.SiteState + " " + project.SitePostalCode); 


       longitude = addresses.First().Coordinates.Latitude.ToString(); 
       latitude = addresses.First().Coordinates.Longitude.ToString(); 

       HttpClient client = new HttpClient(); 
       client.BaseAddress = new Uri("http://forecast.weather.gov/MapClick.php"); 
       string uri = "http://forecast.weather.gov/MapClick.php?lat=" + latitude + "&lon=" + longitude + "&FcstType=dwml"; 

       HttpResponseMessage response = await client.GetAsync(uri); 

       xdoc = XDocument.Parse(await response.Content.ReadAsStringAsync(), LoadOptions.None); 


       Services.Log.Info(xdoc.Descendants("wordedForecast").Descendants("text").ElementAt(0).Value); 


       //Update or create an weather entry for each project 

      } 
     } 







     return;//Task.FromResult(true); 
    } 
} 
+4

我投票结束这个问题作为题外话,因为它质疑weather.com的服务器状态,而不是任何实际的编程问题。 – paqogomez 2015-04-02 20:26:19

+0

我不确定它是否是我的服务器代码。 – ScarletMerlin 2015-04-02 20:26:50

+0

如果你的代码以前工作,并且现在不工作,那么你的代码将如何?无论哪种方式,你应该问weather.com,而不是stackoverflow。 – paqogomez 2015-04-02 20:27:25

回答

5

看起来您的网站更改了政策。它需要设置User-Agent标题。您所需要的只是将其设置为某个值。

var url = "http://forecast.weather.gov/MapClick.php?lat=42&lon=-75&FcstType=dwml"; 
HttpClient client = new HttpClient(); 
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Stackoverflow/1.0"); 
var xml = await client.GetStringAsync(url); 
+2

你先生是我的英雄。我尽我所能,但你救了我。并相信我几乎已经解决了这个问题。它现在有效,非常感谢。 – ScarletMerlin 2015-04-02 20:45:40