2014-10-01 54 views
1

我使用Xamarin形式,我試圖獲得設在這裏的文件的JSON字符串。不過,我似乎無法獲得Json字符串。這是我的代碼:獲取JSON字符串的HttpClient

public async static Task<string> GetJson(string URL) 
{ 
    using (HttpClient client = new HttpClient()) 
    using (HttpResponseMessage response = await client.GetAsync(URL)) 
    using (HttpContent content = response.Content) 
    { 
     // ... Read the string. 
     return await content.ReadAsStringAsync(); 
    } 
} 

private static void FindJsonString() 
{ 
    Task t = new Task(GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json")); 
    t.Start(); 
    t.Wait(); 
    string Json = t.ToString(); 
} 

我在做什麼錯?

我得到關於這些2個錯誤到此線

Task t = new Task(GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json")); 

錯誤1
的最好重載方法匹配 'System.Threading.Tasks.Task.Task(System.Action)' 具有一些無效參數

錯誤2
參數1:無法從 'System.Threading.Tasks.Task' 到 'System.Action' 轉換

+0

您是否收到錯誤?你沒有想到的東西?或者什麼也沒有? – Tim 2014-10-01 05:11:37

+0

它不會因爲該行任務T =新任務(的getJSON(「https://dl.dropboxusercontent.com/u/37802978/policyHolder.json」))的編譯; – Kuzon 2014-10-01 05:14:28

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2014-10-01 05:30:56

回答

2

這是因爲new Task期待一個Action代表,而你傳遞一個Task<string>

不要使用new Task,使用Task.Run。此外,請注意,你傳遞一個async方法,你可能要await GetJson

所以,你要麼需要

var task = Task.Run(() => GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json")); 

或者,如果你想awaitTask.Run

var task = Task.Run(async() => await GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json")); 

他們在回報類型上也會有所不同。前者將返回Task<Task<string>>,而後者將返回Task<string>

TPL準則狀態異步方法應該以Async後綴結束。考慮重命名GetJsonGetJsonAsync

+0

謝謝你回答@Yuval。但是,如何從GetJson獲取返回字符串?是在var任務? – Kuzon 2014-10-01 05:39:28

+0

'await'語義上從返回類型中刪除任務。所以,'等待GetJson()'是Json字符串。在一個任務上調用'.Result'也會得到相同的結果,但是會阻塞你的線程。 – 2014-10-01 05:44:16

+0

當Task.Run完成時,您可以在task.Result中訪問它。請注意,如果您在任務完成之前訪問「Result」屬性,則它將像同步方法一樣阻止**。 – 2014-10-01 06:02:48