본문 바로가기

개발일지

Rest API json 호출 테스트 java 실습

728x90

각 시스템 간에 인터페이스 를 Rest API를 호출하여 사용하기로 결정을 하여 JAVA 버젼과 C#에 대하여 테스트를 진행중에 있다.

Restful API 호출하는 부분에 대하여 아래 사이트를 참고 하였습니다.

docs.agora.io/en/All/faq/restful_authentication

 

How can I pass the basic HTTP authentication or token authentication?

Documentation FAQ Integration issues How can I pass the basic HTTP authentication or token authentication? Introduction Before using the Agora RESTful API, you need to pass basic HTTP authentication or token authentication. Basic HTTP authentication You ne

docs.agora.io

 

우선 아래 스웨거로 일단 초기 테스트를 먼저 해봅니다.

보통의 경우 url에 파라미터를 추가하여 호출하는 경우로 확인가능

이제 자바소스에서 이 서비스를 호출하는 예제 테스트 합니다.

    public static String sendREST(String sendUrl, String jsonValue) throws IllegalStateException {
        String inputLine = null;
        StringBuffer outResult = new StringBuffer();
        
        try {
            System.out.println("REST API Start");
            URL url = new URL(sendUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            /****** 인증이 있는경우 
            String id_pass = "id:password";
            String base64Credentials = new String(Base64.getEncoder().encode(id_pass.getBytes()));
            conn.setRequestProperty("Authorization", "Basic " + base64Credentials);
            */
            
            OutputStream os = conn.getOutputStream();
            os.write(jsonValue.getBytes("UTF-8"));
            os.flush();
            
            // 리턴된 결과 읽기
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((inputLine = in.readLine()) != null) {
                outResult.append(inputLine);
            }
            
            conn.disconnect();
            System.out.println("REST API End");
        }catch(Exception e) {
            e.printStackTrace();
        }
        return outResult.toString();
    }

Case1 : 파라미터 호출인 경우  간단하게 처리하면 됨.

String msgMap = sendREST("http://localhost:8080/api/hello?name=12", null);

Case2 : 데이터를 json 형식으로 전달해야 하는 경우

HashMap<String, Object> resultMap = new HashMap();
resultMap.put("key", "data");
ObjectMapper mapper = new ObjectMapper();

try {
	String json = mapper.writeValueAsString(resultMap);
    String msgMap = sendREST("http://localhost:8080/api/hello", json);
    System.out.println(msgMap);
}catch(Exception e) {
	e.printStackTrace();
}
728x90