2015-01-05 60 views
1

我是新來的C#編程。 我想用openweathermap API開發一個簡單的天氣應用程序。 我想從URL下載並閱讀文件的內容。無法從網址下載字符串C#Windows 8.1

這是我的代碼,下載文件的內容:

class WebClientToDownload 
{ 
    string webresponse; 

    public async void DownloadFile(string url) 
    { 
     string baseurl = "http://api.openweathermap.org/data/2.5/forecast/daily?q="; 
     StringBuilder sb = new StringBuilder(baseurl); 
     sb.Append(url + "&mode=json&units=metric&cnt=7"); 
     string actual = sb.ToString(); 
     HttpClient http = new System.Net.Http.HttpClient(); 
     HttpResponseMessage response = await http.GetAsync(actual); 
     webresponse = await response.Content.ReadAsStringAsync();   
    } 

    public string StringReturn() 
    { 
     return webresponse; 
    } 

字符串傳遞給函數的是城市的名稱。 這是代碼的MainPage,我調用這些函數:

string JSONData; 
    private void GetWeatherButton_Click(object sender, RoutedEventArgs e) 
    { 
     WebClientToDownload Cls = new WebClientToDownload(); 
     Cls.DownloadFile(GetWeatherText.Text); 
     JSONData = Cls.StringReturn(); 
     JSONOutput.Text = JSONData; 
    } 

我在代碼最後一行得到一個錯誤,說是

An exception of type 'System.ArgumentNullException' occurred in mscorlib.dll but was not handled in user code 

Additional information: Value cannot be null. 
+1

歡迎來到StackOverflow。請提供有關您所得確切錯誤的更多詳細信息。 – Polyfun

+0

你有錯誤嗎?當你運行代碼時會發生什麼? – M4N

+0

對不起,我忘了添加錯誤詳細信息:當我嘗試獲取數據時,字符串webresponce爲空 –

回答

1

它看起來就像是到你使用的await的。基本上,await會將控制傳遞迴調用函數,並允許它繼續下去,直到它被等待,這不會發生在您的情況中,因此它在數據返回之前調用Cls.StringReturn()。您可以更改如下:

在您的形式:

string JSONData; 
// Note the async keyword in the method declaration. 
private async void GetWeatherButton_Click(object sender, EventArgs e) 
{ 
    WebClientToDownload Cls = new WebClientToDownload(); 
    // Notice the await keyword here which pauses the execution of this method until the data is returned. 
    JSONData = await Cls.DownloadFile(GetWeatherText.Text); 
    JSONOutput.Text = JSONData; 
} 

在下載類:

class WebClientToDownload 
{ 
    // Notice this now returns a Task<string>. This will allow you to await on the data being returned. 
    public async Task<string> DownloadFile(string url) 
    { 
     string baseurl = "http://api.openweathermap.org/data/2.5/forecast/daily?q="; 
     StringBuilder sb = new StringBuilder(baseurl); 
     sb.Append(url + "&mode=json&units=metric&cnt=7"); 
     string actual = sb.ToString(); 
     HttpClient http = new System.Net.Http.HttpClient(); 
     HttpResponseMessage response = await http.GetAsync(actual); 
     // Return the result rather than setting a variable. 
     return await response.Content.ReadAsStringAsync(); 
    } 
} 

我已經測試過,並返回有效的數據,但如果任何這不是清楚,請讓我知道。

+0

知道了!!非常感謝 –