import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.net.URL;
public class CallAPI {
public static void main(String[] args) {
String userName = "<사용자 서비스 ID>"; // Change it
String password = "<사용자 서비스 Password>"; //Change it
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("userName", userName);
jsonObject.addProperty("password", password);
String apiURL = "https://service.mqnicrnd5.com/auth";
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("Content-Type", "application/json; utf-8");
String responseBody = post(apiURL, jsonObject, requestHeaders);
System.out.println(responseBody);
}
private static String post(String apiUrl, JsonObject requestBody, Map<String, String> requestHeaders) {
HttpURLConnection con = connect(apiUrl);
try {
con.setRequestMethod("POST");
con.setDoOutput(true);
for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
Gson gson = new Gson();
String jsonRequestBody = gson.toJson(requestBody);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
byte[] postData = jsonRequestBody.getBytes();
wr.write(postData);
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
return readBody(con.getInputStream());
} else { // 오류 발생
return readBody(con.getErrorStream());
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
con.disconnect();
}
}
private static HttpURLConnection connect(String apiUrl) {
try {
URL url = new URL(apiUrl);
return (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
} catch (IOException e) {
throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
}
}
private static String readBody(InputStream body) {
InputStreamReader streamReader = new InputStreamReader(body);
try (BufferedReader lineReader = new BufferedReader(streamReader)) {
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("API 응답을 읽는 데 실패했습니다.", e);
}
}
}