📌 Rest API 연결
- Http, Https 프로토콜 타입별로 처리
- HttpURLConnection 연결에 대해 가이드 샘플 구성
Rest Api Client
📌 예제 코드
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class RestApiClient {
public static String sendHttpRequest(String targetUrl, String method, String jsonBody) {
StringBuilder response = new StringBuilder();
HttpURLConnection conn = null;
OutputStream os = null;
BufferedReader br = null;
try {
URL url = new URL(targetUrl);
if (targetUrl.startsWith("https")) {
conn = (HttpsURLConnection) url.openConnection();
} else {
conn = (HttpURLConnection) url.openConnection();
}
conn.setRequestMethod(method);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
if (jsonBody != null && jsonBody.length() > 0) {
os = conn.getOutputStream();
os.write(jsonBody.getBytes("UTF-8"));
}
int responseCode = conn.getResponseCode();
System.out.println("HTTP Response Code: " + responseCode);
br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
} catch (IOException e) {
System.err.println("HTTP 요청 중 오류 발생: " + e.getMessage());
} finally {
try {
if (os != null) os.close();
if (br != null) br.close();
if (conn != null) conn.disconnect();
} catch (IOException e) {
System.err.println("리소스 해제 중 오류 발생: " + e.getMessage());
}
}
return response.toString();
}
public static void main(String[] args) {
String url = "https://example.com/api";
String method = "POST";
String jsonBody = "{\"message\":\"Hello, API!\"}";
String response = sendHttpRequest(url, method, jsonBody);
System.out.println("Response: " + response);
}
}
📌 출력 결과:
HTTP Response Code: 200
Response: {"status":"success","data":"Hello, Client!"}
'프로그램 > Java' 카테고리의 다른 글
| [Java] Date 객체와 날짜 처리 방법 (0) | 2025.03.13 |
|---|---|
| [Java] HttpURLConnection으로 HTTP/HTTPS 연결 구현하기 (0) | 2025.02.26 |
| 예쁜꼬마선충의 신경 연결 지도를 활용하여 로봇에 인공지능(AI) 프로그램 (0) | 2025.02.25 |
| 예쁜꼬마선충 뇌정보를 이해하고 이용한 Java 프로그램 (0) | 2025.02.25 |
| [Java] 복사 대상 파일의 최상위 폴더 구조 포함하여 복사 (0) | 2025.02.25 |