본문 바로가기

New Spring

java RESTAPI

@RequestMapping(value="/restapi", method = RequestMethod.GET)
public String pipeline() throws Exception {

logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 1");

HttpURLConnection conn = null;
JsonObject params = new JsonObject();

logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 2");

try {
            //URL 설정
            URL url = new URL("해당URL주소");
 
            conn = (HttpURLConnection) url.openConnection();
            
            // type의 경우 POST, GET, PUT, DELETE 가능
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Transfer-Encoding", "chunked");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setDoOutput(true);
            
            logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 3");

            logger.info("conn ~~~~~~~~~~~~~~~~~~~ : "+conn);
            
//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
//            
//            logger.info("bw ~~~~~~~~~~~~~~~~~~~ : "+bw);
            
            
            logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 4");
            
          
            logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 5");
            
           
            
            logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 6");
            
            // 보내고 결과값 받기
            int responseCode = conn.getResponseCode();
            
            logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 7");
            
            logger.info("responseCode ~~~~~~~~~~~~~~~~~~~ : "+responseCode);
            
            if (responseCode == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                
                JSONObject responseJson = new JSONObject(sb.toString());
                
                logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 8");
                
                // 응답 데이터
                System.out.println("responseJson :: " + responseJson);
                
                logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 9");
            } else {
             logger.info("restapi ~~~~~~~~~~~~~~~~~~~ 10");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


return "/test";
}

'New Spring' 카테고리의 다른 글

ajax json 전송  (0) 2020.09.16
JSON 자바출력 (jackson)  (0) 2020.09.02
JSON 자바 출력 (json-simple)  (0) 2020.08.30