2014-10-01 51 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