-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREST_API:_Weather_Finder.cs
87 lines (73 loc) · 2.54 KB
/
REST_API:_Weather_Finder.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
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
class Result
{
/*
* Complete the 'getTemperature' function below.
*
* URL for cut and paste
* https://jsonmock.hackerrank.com/api/weather?name=<name>
*
* The function is expected to return an Integer.
* The function accepts a singe parameter name.
*/
private static readonly HttpClient client = new HttpClient();
public static int getTemperature(string name)
{
// Create the URL with the provided city name
string url = $"https://jsonmock.hackerrank.com/api/weather?name={name}";
try
{
// Perform an HTTP GET request to fetch weather information
HttpResponseMessage response = client.GetAsync(url).Result;
// Check if the response is successful
if (response.IsSuccessStatusCode)
{
// Read the response content as string
string responseBody = response.Content.ReadAsStringAsync().Result;
// Deserialize the JSON response
dynamic weatherData = Newtonsoft.Json.JsonConvert.DeserializeObject(responseBody);
// Extract the temperature from the first weather record
string weather = weatherData.data[0].weather;
int temperature = int.Parse(weather.Split(' ')[0]); // Extract integer part
return temperature;
}
else
{
throw new Exception($"Failed to fetch weather data for {name}. Status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
// Handle any exceptions and return -1 indicating failure
Console.WriteLine($"An error occurred: {ex.Message}");
return -1;
}
}
}
class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string name = Console.ReadLine();
int result = Result.getTemperature(name);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}