Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion spring-http-client-1/initial/src/main/java/cholog/Todo.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@
public class Todo {

// TODO: Todo 객체가 가지는 필드들을 정의
private Long id;
private Long userId;
private String title;
private boolean completed;

public String getTitle() {
return null;
return this.title;
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package cholog;

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatusCode;
import org.springframework.web.client.RestClient;

import java.util.Collections;
Expand All @@ -13,13 +16,19 @@ public TodoClientWithRestClient(RestClient restClient) {
}

public List<Todo> getTodos() {
// TODO: restClient의 get 메서드를 사용하여 요청을 보내고 결과를 Todo 리스트로 변환하여 반환
return Collections.emptyList();
return restClient.get()
.uri("/todos")
.retrieve()
.body(new ParameterizedTypeReference<List<Todo>>(){});
}

public Todo getTodoById(Long id) {
// TODO: restClient의 get 메서드를 사용하여 요청을 보내고 결과를 Todo로 변환하여 반환
// TODO: 존재하지 않는 id로 요청을 보낼 경우 TodoException.NotFound 예외를 던짐
return new Todo();
return restClient.get()
.uri("/todos/{todoId}", id)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, (request, response) -> {
throw new TodoException.NotFound(id);
})
.body(Todo.class);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package cholog;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

public class TodoClientWithRestTemplate {
private final RestTemplate restTemplate;
Expand All @@ -10,8 +16,16 @@ public TodoClientWithRestTemplate(RestTemplate restTemplate) {
}

public Todo getTodoById(Long id) {
// TODO: restTemplate을 사용하여 요청을 보내고 결과를 Todo로 변환하여 반환
// TODO: 존재하지 않는 id로 요청을 보낼 경우 TodoException.NotFound 예외를 던짐
return new Todo();

URI uri = UriComponentsBuilder
.fromHttpUrl("http://jsonplaceholder.typicode.com")
.path("/todos/{todoId}")
.build(id);

try {
return restTemplate.getForEntity(uri, Todo.class).getBody();
} catch (HttpClientErrorException e) {
throw new TodoException.NotFound(id);
}
}
}