| 메서드 | 역할 (Action) | 바디(Body) | 멱등성* | 주요 응답 코드 | 비유 |
|---|---|---|---|---|---|
| GET | 조회 (Read) | X | Yes | 200 (OK) | 도서관에서 책 찾아보기 |
| POST | 생성 (Create) | O | No | 201 (Created) | 게시판에 새 글 쓰기 |
| PUT | 수정 (Update) | O | Yes | 200 (OK) | 헌 가구를 새 가구로 교체 |
| DELETE | 삭제 (Delete) | X | Yes | 200 (OK) / 204 | 휴지통에 버리기 |

DTO 설계
package http.http_client.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Post {
private Integer id;
private Integer userId;
private String title;
private String body;
@Builder
public Post(Integer id, Integer userId, String title, String body) {
this.id = id;
this.userId = userId;
this.title = title;
this.body = body;
}
}
DTO는 Data Transfer Object라고 데이터를 옮길 객체이다.
먼저 Json 파싱을 처리한걸 받을 DTO을 설계한다.
GET 요청
package http.http_client;
import com.google.gson.Gson;
import generic.ch03.Powder;
import http.http_client.dtos.Post;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpGetParsingEx {
public static void main(String[] args) {
// 1. HttpClient와 Gson 준비
HttpClient client = HttpClient.newHttpClient(); // new HttpClient
Gson gson = new Gson();
try {
// 2. HTTP 요청 메세지 생성 (요청 생성)
// HttpRequest <--- 객체를 생성해주는 녀석
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.GET()
.build();
// 3. 응답 받기
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
// 4. 응답 내용 확인 (로깅) -> HTTP 응답 메세지가 들어 옴
System.out.println("response : " + response);
System.out.println("response : " + response.body());
// 5. 파싱 처리 하기 .
Post post = gson.fromJson(response.body(), Post.class);
System.out.println("====파싱완료======");
System.out.println("게시글 ID " + post.getId());
System.out.println("작성자 ID " + post.getUserId());
System.out.println("게시글 제목 " + post.getTitle());
System.out.println("게시글 본문 " + post.getBody());
} catch (Exception e) {
throw new RuntimeException(e);
}
} // end of main
}
그다음 http에 요청을 하여 응답을 받고 파싱처리를 하는 모습이다.