반응형

POST 방식으로 간단하게 REST API 호출하는 방법

 

아래와 같이 호출을 하게 되면 String 타입의 json 이라는 변수에 응답받게 된다.

URL obj = null;
String json = "";

String WEB_ID = URLEncoder.encode("테스트아이디","UTF-8");
String WEB_PW = URLEncoder.encode("테스트암호","UTF-8");

Map<String, Object> params = new HashMap<String, Object>();
params.put("memberId", WEB_ID);
params.put("memberPwd", WEB_PW);

StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet()) {
    if(postData.length() != 0) postData.append('&');
    postData.append(param.getKey());
    postData.append('=');
    postData.append(param.getValue());
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
	
obj = new URL("API 호출 주소");

HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
con.setDoOutput(true);
con.getOutputStream().write(postDataBytes);

BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
	response.append(inputLine);
}
in.close();

json = response.toString();

 

반응형

+ Recent posts