-
Notifications
You must be signed in to change notification settings - Fork 578
Expand file tree
/
Copy pathWeatherClient.java
More file actions
64 lines (50 loc) · 2.14 KB
/
WeatherClient.java
File metadata and controls
64 lines (50 loc) · 2.14 KB
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
package org.example.expert.client;
import org.example.expert.client.dto.WeatherDto;
import org.example.expert.domain.common.exception.ServerException;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@Component
public class WeatherClient {
private final RestTemplate restTemplate;
public WeatherClient(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public String getTodayWeather() {
ResponseEntity<WeatherDto[]> responseEntity =
restTemplate.getForEntity(buildWeatherApiUri(), WeatherDto[].class);
WeatherDto[] weatherArray = responseEntity.getBody();
if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
throw new ServerException("날씨 데이터를 가져오는데 실패했습니다. 상태 코드: " + responseEntity.getStatusCode());
}
// 리얼 else문 제거하기
if (weatherArray == null || weatherArray.length == 0) {
throw new ServerException("날씨 데이터가 없습니다.");
}
String today = getCurrentDate();
for (WeatherDto weatherDto : weatherArray) {
if (today.equals(weatherDto.getDate())) {
return weatherDto.getWeather();
}
}
throw new ServerException("오늘에 해당하는 날씨 데이터를 찾을 수 없습니다.");
}
private URI buildWeatherApiUri() {
return UriComponentsBuilder
.fromUriString("https://f-api.github.io")
.path("/f-api/weather.json")
.encode()
.build()
.toUri();
}
private String getCurrentDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");
return LocalDate.now().format(formatter);
}
}