IT정보사전

[JAVA] REST API 전송 (Json Post Request) 본문

웹 프로그래밍

[JAVA] REST API 전송 (Json Post Request)

작은나무0530 2018. 12. 7. 14:05
728x90
반응형

안녕하세요~ 작은나무입니다!!

REST API방식을 많이 사용하는 것 같습니다. 
JSON Data를 Post전송하는 방법을 정리해 보겠습니다.


public static String sendREST(String sendUrl, String jsonValue) throws IllegalStateException {

String inputLine = null;
StringBuffer outResult = new StringBuffer();

  try{
	logger.debug("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);
      
	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();
	logger.debug("REST API End");        
  }catch(Exception e){
      logger.error(e.getMessage(), e);
      e.printStackTrace();
  }	
  
  return outResult.toString();
}


[호출하기]

HashMap<String, Object> resultMap = new HashMap();
resultMap.put("DATA", param.getString("DATA"));    //파라미터 설정
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(resultMap);    //convert map to JSON String(JSON으로 변환)

String msgMap = sendREST("http:localhost", json);
728x90
반응형
그리드형
Comments