Last active
April 4, 2020 21:25
-
-
Save obrassard/9c11b262ed3a092bceb0cf95961c2ca9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ curl -s https://icanhazdadjoke.com/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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