Programming > JSP/HTML/JSTL

jsp 에서 http post 요청하기 샘플소스

JSP 에서 테스트용으로 post 요청보내기

※ sendPost.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.net.*, java.util.*, javax.net.ssl.HttpsURLConnection" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%

    String getParam(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        for(String key : map.keySet()) {
            if(isFirst) {
                isFirst = false;
            } else {
                sb.append("&");
            }
            sb.append(key).append("=").append(map.get(key));
        }
       
        return sb.toString();
    }
   
    String sendPost(String targetURL, String urlParameters) throws Exception {
        
        StringBuffer response = new StringBuffer();
        URI uri = new URI(targetURL);
        URL url = uri.toURL();
        
        try {
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
   
            // HTTP 메서드와 헤더 설정
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "ko");
   
            connection.setUseCaches(false);
            connection.setDoOutput(true); // POST 데이터를 전송할 수 있도록 설정
   
            // Request Body에 데이터 전송
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.writeBytes(urlParameters);
                wr.flush();
            }
   
            // 응답 읽기
            InputStream is;
            if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 300) {
                is = connection.getInputStream(); // 성공적인 응답
            } else {
                is = connection.getErrorStream(); // 오류 응답
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;
   
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
   
        return response.toString(); // 응답 문자열 리턴
    }
   
    Map<String,String> map = new HashMap<String, String>();
   
    String targetURL = "https://emunhi.com/api";
    map.put("id", "hodu");
    map.put("name", "킹 호두");
    map.put("content","hello 나는 호두");
   
   
    String urlParameters = getParam(map);
   
   
    // POST 요청을 보내고 결과를 출력
    try {
        String result = sendPost(targetURL, urlParameters);
        System.out.println("Response: " + result);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error: " + e.getMessage());
    }
%>

</body>
</html>