Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 865
Steen Schütt Avatar asked May 27 '26 12:05

Steen Schütt


2 Answers

Since the GetAsync is a task you can do

     rq.GetAsync(uri).ContinueWith((requestTask) => SomeMethod(requestTask););
like image 191
TYY Avatar answered May 30 '26 11:05

TYY


HttpResponseMessage response = await rq.GetAsync(uri);

//put here your continuation logic. 
like image 41
Hamlet Hakobyan Avatar answered May 30 '26 11:05

Hamlet Hakobyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!