Reputation:
I'd like to print the contents of a HTTPResponseMessage.
class Requests
{
public static async Task SendRequest(int port, string path, KVPairs kvPairs)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASE_ADDRESS + port);
var request = new HttpRequestMessage(HttpMethod.Put, path);
request.Content = new FormUrlEncodedContent(kvPairs);
ProcessResponse(await client.SendAsync(request));
}
}
public static void ProcessResponse (HttpResponseMessage response)
{
Console.WriteLine(response.Content.ReadAsStringAsync());
}
}
SendRequest works perfectly. But ProcessResponse() prints System.Threading.Tasks.Task\`1[System.String]
How can I access and print the contents of the response? Thank you!
Upvotes: 1
Views: 5130
Reputation: 36473
You need to await the task returned by response.Content.ReadAsStringAsync()
, which in turn means you need to make ProcessResponse
an async
method, and await on that too. Otherwise, you are printing out the task object itself, which is not what you want.
Notice the 3 changes below (see comments):
public static async Task SendRequest(int port, string path, KVPairs kvPairs)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(BASE_ADDRESS + port);
var request = new HttpRequestMessage(HttpMethod.Put, path);
request.Content = new FormUrlEncodedContent(kvPairs);
await ProcessResponse(await client.SendAsync(request)); // added await here
}
}
public static async Task ProcessResponse (HttpResponseMessage response) // added async Task here
{
Console.WriteLine(await response.Content.ReadAsStringAsync()); // added await here
}
Upvotes: 4
Reputation: 501
This solution should work for you. Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern
You should use await or wait() to get the response and then process it like this:
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);
Upvotes: 0