코딩 관련/Java
[JAVA] API 호출하기 / URI 요청하기 / URI 생성하기
메리짱123
2022. 6. 3. 15:05
반응형
필요한 내용은 다음과 같다.
1. post 메소드로 요청하는 경우
헤더 생성 + uri 생성 + body부 데이터 생성 => RestTemplate 으로 url 요청하기
2. GET 메소드로 요청하는 경우
헤더 생성 + uri 생성(파라미터가 있는 경우 붙여준다) => RestTemplate으로 url 요청하기
//ResTemplate 생성
RestTemplate restTemplate = new RestTemplate();
//헤더 생성
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "*/*");
headers.add("Content-Type", "application/json;charset=UTF-8");
//url 생성
URI url = URI.create("http://localhost:8888/api/test");
//POST로 보내는 경우 : body에 실어보낼 json데이터 생성
JSONObject jsonReq = new JSONObject();
jsonReq.put("data1", "data1");
jsonReq.put("data2", "data2");
HttpEntity<String> entity = new HttpEntity<>(jsonReq.toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//GET으로 보내는 경우 : 쿼리파라미터는 url에 붙여 보내면 댐
RequestEntity<String> req = new RequestEntity<>(headers, HttpMethod.GET, url);
ResponseEntity<String> res = restTemplate.exchange(req, String.class);
반응형