Spring에서 API를 호출할 때 질문좀요..
조회수 782회
A서버랑 B서버가 있고, 서로 네트워크 망이 다르고 보안이슈 때문에 디비링크를 연결하지 못합니다.
그래서 데이터를 가지고 있는 A서버에서 API를 통해 데이터를 가져와야는데요, A서버는 API 제공자니까 CRUD(생성, 읽기, 수정, 삭제) 4개의 매소를 만들어서 제공을 해주는게 맞잖아요?? (읽기(R)는 get으로, 나머지 생성,수정,삭제(CUD)는 post로)
그런데 해당 API를 호출하는 B서버도 4개를 만들어서 관리를 해야 하나요?
저는 지금 get으로 호출하는것 하나, post로 호출하는것 하나 해서 두가지를 공통 클래스 안에 만들어놓고 각 컨트롤러에서 필요에 따라서 호출(get or post)을 하는데
@Controller
@RequestMapping("/user")
public class UserController {
CaController caController = new CaController();
...
//데이터 가져올 때
@RequestMapping(value="getUserInfo.do")
public ModelAndView getUserInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam Map<String, Object> data) throws Exception {
...
//get방식
String result = caController.getMethod(data);
...
}
...
//데이터 삭제(생성, 수정, 삭제 동일.. deleteUserInfo, updateUserInfo, createUserInfo)
@RequestMapping(value="deleteUserInfo.do")
public ModelAndView deleteUserInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam Map<String, Object> data) throws Exception {
...
//post방식
String result = caController.postMethod(data);
...
}
이 방법으로 해도 맞는건지 궁금합니다.
1) get 방식으로 사용하는 함수(데이터를 가져올 때)
public String getMethod(@RequestParam Map<String, Object> data) throws Exception {
URL url = new URL(data.url);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
StringBuffer sb = new StringBuffer();
String tempStr = null;
while(true) {
tempStr = br.readLine();
if(tempStr == null) break;
sb.append(tempStr);
}
br.close();
return sb.toString();
}
2) post 방식으로 사용하는 함수(데이터 생성, 수정, 삭제)
public String postMethod(@RequestParam Map<String, Object> data) throws Exception {
String iStr = null;
StringBuffer outBuf = new StringBuffer();
String param = getJsonStringForMap(data);
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept-Charset", "UTF-8");
OutputStream os = conn.getOutputStream();
os.write(param.getBytes("UTF-8"));
os.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while((iStr = in.readLine()) != null) {
outBuf.append(iStr);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return outBuf.toString();
}
아니면 다른 방법으로 하는게 맞는지 궁금합니다..
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력