-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFetcher.cs
115 lines (99 loc) · 3.51 KB
/
Fetcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using Newtonsoft.Json.Linq;
using VendingMachine.Products;
namespace VendingMachine;
public abstract class Fetcher
{
public static async Task<Quote> GetRandomQuote()
{
string baseUrl = "https://api.quotable.io/quotes/random?maxLength=75";
try
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
var dataParsed = JArray.Parse(data)[0];
Quote quote = new Quote(dataParsed["content"].ToString(), dataParsed["author"].ToString());
return quote;
}
// (if null:)
Quote altQuote = new Quote("The quote API seems to be broken...", "Joar Hansson");
return altQuote;
}
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
return null;
}
}
public static async Task<CatFact> GetRandomCatFact()
{
string baseUrl = "https://meowfacts.herokuapp.com";
try
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
var dataParsed = JObject.Parse(data);
CatFact catFact = new CatFact(dataParsed["data"][0].ToString());
return catFact;
}
// (if null:)
CatFact altCatFact = new CatFact("The cat API seems to be broken...");
return altCatFact;
}
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
return null;
}
}
public static async Task<DogFact> GetRandomDogFact()
{
string baseUrl = "https://dogapi.dog/api/facts";
try
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage res = await client.GetAsync(baseUrl))
{
using (HttpContent content = res.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
var dataParsed = JObject.Parse(data);
DogFact dogFact = new DogFact(dataParsed["facts"][0].ToString());
return dogFact;
}
// (if null:)
DogFact altDogFact = new DogFact("The dog API seems to be broken...");
return altDogFact;
}
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
return null;
}
}
}