简体   繁体   中英

How do I create a callback in C# (.NET 4.5) for HttpClient.GetAsync(URI)?

I'd like to create a simple, async request to Google search.

According to Google, the simplest way to do this is using their JSON API with the simple curl request

curl -e http://www.my-ajax-site.com \ 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton'

I'd like to pull the first 5 pages of results and add the URL's of each result to an array. I find it unbelievably difficult to find any well-explained tutorials on HttpClient.GetAsync. I haven't got any further than this:

public String[] search(String term = "")
{
    var rq = new HttpClient();
    var uri = new Uri("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:" + term);
    rq.GetAsync(uri);
}

I suppose this should start a task so I won't block the main thread, but how do I register a callback method for when the request is completed?

由于GetAsync是一项任务,您可以执行

     rq.GetAsync(uri).ContinueWith((requestTask) => SomeMethod(requestTask););
HttpResponseMessage response = await rq.GetAsync(uri);

//put here your continuation logic. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM