2015-04-02 247 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