HttpURLConnection을 통해 서버로 api 요청이 가능하다.
이 방식은 JDK11 버전 이전 사용하던 방식으로 권장되지 않는 방식이므로
JDK11버전 이상의 프로젝트를 진행중이라면 HttpClient를 사용하도록 하자.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class RestService {
public static void main(String[] args) {
// 테스트용 JSON 데이터 생성
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "John Doe");
jsonParam.put("age", 30);
// API 호출
String apiUrl = "http://test.com";
JSONObject response = sendPost(apiUrl, jsonParam);
System.out.println(response);
}
public static JSONObject sendPost(String apiUrl, JSONObject jsonParam) {
HttpURLConnection conn = null;
BufferedReader br = null;
JSONObject responseJson = null;
try {
// URL 객체 생성
URL url = new URL(apiUrl);
conn = (HttpURLConnection) url.openConnection();
// HTTP POST 설정
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// JSON 데이터 전송
OutputStream os = conn.getOutputStream();
os.write(jsonParam.toString().getBytes());
os.flush();
os.close();
// HTTP 응답 읽기
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder responseStr = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
responseStr.append(line);
}
// 응답 JSON 파싱
responseJson = new JSONObject(responseStr.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
// 자원 해제
if (conn != null) {
conn.disconnect();
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return responseJson;
}
}
'BackEnd > JAVA' 카테고리의 다른 글
[eclipse] TLS 접속오류 해결 (0) | 2023.07.28 |
---|