Skip to content

Instantly share code, notes, and snippets.

@obrassard
Last active April 4, 2020 21:25
Show Gist options
  • Save obrassard/9c11b262ed3a092bceb0cf95961c2ca9 to your computer and use it in GitHub Desktop.
Save obrassard/9c11b262ed3a092bceb0cf95961c2ca9 to your computer and use it in GitHub Desktop.
$ curl -s https://icanhazdadjoke.com/
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace JokesAPI
{
public class DadJokeService
{
private readonly HttpClient client;
public DadJokeService()
{
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://icanhazdadjoke.com");
}
public string GetRandomJoke()
{
HttpResponseMessage response = client.GetAsync("/").Result;
if (response.IsSuccessStatusCode)
{
string jsonResponse = response.Content.ReadAsStringAsync().Result;
JokeResponse jokeResponse = JsonSerializer.Deserialize<JokeResponse>(jsonResponse);
return jokeResponse.Content;
}
else
{
throw new HttpRequestException(string.Format("{0} ({1})", response.StatusCode, response.ReasonPhrase));
}
}
private class JokeResponse
{
[JsonPropertyName("joke")]
public string Content { get; set; }
[JsonPropertyName("id")]
public string Id { get; set; }
[JsonPropertyName("status")]
public int Status { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment