Spring Boot를 통해 외부(SAP)에서 우리DB에 저장하고 조회, 우리가 외부에 접속해서 저장하고 조회 하는 API를 구현함.
1,2번에 대한 상세한 내용은 링크 참조 API GET, POST
@GetMapping("/select")
public List<Test> tests() {
System.out.println(testServices.selectAll().toString());
return testServices.selectAll();
}
@PostMapping("/save")
public Test save(@RequestBody Test test){
new ResponseEntity<Test>(testServices.save(test), HttpStatus.OK);
return test;
}
@GetMapping("/sapselect")
public String sapselect()
{
try {
URL url = new URL("주소");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 하단 3개 property는 sap에 post시 인증, 토큰, 쿠키값이 필요해서 Get시 받음
// 외부 환경에 따라 변경해서 사용
conn.setRequestProperty("Authorization", "Basic 인증키 값");
conn.setRequestProperty("x-csrf-token", "fetch");
conn.setRequestProperty("set-cookie", "fetch");
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
Map<String, List<String>> map = conn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
if ("x-csrf-token".equals(entry.getKey())) {
token = entry.getValue().get(0);
}
if ("set-cookie".equals(entry.getKey())) {
cookie = entry.getValue().get(0).split(";")[0];
}
}
return br.readLine();
}
catch (Exception e) {
return e.getMessage();
}
}
@PostMapping("/sapset")
public void sapset()
{
try
{
URL url = new URL("주소");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// sap와 post하기 위해 작성한 값으로 무시해도 됨.
conn.setRequestProperty("x-csrf-token", token);
conn.setRequestProperty("Authorization", "Basic 인증키 값");
conn.setRequestProperty("Cookie", cookie);
conn.setDoInput(true); // 서버에 전달할 값이 있다면 true
conn.setDoOutput(true); // 서버에서 받을 값이 있다면 true
// 보낼 데이터 생성
JSONObject obj = new JSONObject();
obj.put("ID", "테스트");
// buffer로 데이터 전달
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
bw.write(obj.toString());
bw.flush();
bw.close();
// buffer로 데이터 수신
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//printing response
System.out.println(response.toString());
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
JSONObject 사용시 dependency 추가 해줘야함.
Gradle
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'