HTTP 클라이언트 API 도입
// HTTP 클라이언트 생성
HttpClient httpClient = HttpClient.newHttpClient();
// GET
HttpRequest getRequest = HttpRequest.newBuilder()
.uri(new URI("https://backend.opsnow.com:9137/api/menu/list"))
.header("Authorization", "Bearer *********")
.GET()
.build();
HttpResponse<String> response = httpClient.send(getRequest, HttpResponse.BodyHandlers.ofString());
// =====================================================================================
// POST
// Payload 1 - DTO
User user = User.builder()
.name("양승길")
.email("seunggil.yang@bespinglobal.com")
.build();
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(user);
// Payload 2 - JSONObject
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("field1", "value1");
jsonRequest.put("field2", "value2");
String requestBody = jsonRequest.toString();
// Payload 3 - Map
Map<String, String> requestData = Map.of(
"field1", "value1",
"field2", "value2"
);
String requestBody = new JSONObject(map).toString();
// POST 요청 생성
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(new URI("https://backend.opsnow.com:9137/api/join"))
.header("Authorization", "Bearer *********")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(postRequest, HttpResponse.BodyHandlers.ofString());
// =====================================================================================
// 응답 처리
if (response.statusCode() == 200) {
System.out.println("POST Response Body: " + response.body());
ObjectMapper objectMapper = new ObjectMapper();
ResponseDto response = objectMapper.readValue(response.body(), ResponseDto.class);
} else {
System.err.println("POST Request Failed with Status Code: " + response.statusCode());
}
String 관련 메서드 추가
// 1. 공백 확인
String str = " ";
boolean isBlank = str.isBlank(); // true
// 2. 앞뒤 공백 제거
String str = " Hello, World! ";
String stripped = str.strip(); // "Hello, World!"
// trim()과의 차이
// strip() - 공백(space), 탭(tab), 줄 바꿈(newline) 등의 유니코드 공백 문자 제거
// trim() - 공백(space), 탭(tab)만 제거
// 3. 반복
String repeated = "abc".repeat(3); // "abcabcabc"
// 4. List화
String multiLineString = "Line 1\nLine 2\r\nLine 3";
List<String> lines = multiLineString.lines()
.collect(Collectors.toList());
// 5. 포맷
String formattedString = "Hello, %s! Today is %d %s.".formatted("John", 22, "September");
반응형
'Java > History' 카테고리의 다른 글
Java 17 대표 코드 (0) | 2024.12.16 |
---|---|
Java 15, 16 대표 코드 (0) | 2024.12.16 |
Java 12~14 대표 코드 (0) | 2024.12.16 |
Java 9, 10 대표 코드 (0) | 2024.12.16 |
Java 8 대표 코드 (1) | 2024.12.16 |