반응형
[JAVA 실습 #3] http통신, REST API호출, json 데이터 처리 후 출력
<< 개발환경 >>
Windows
JDK1.8
Eclipse
<< 실습과정 >>
1. url: dummy.restapiexample.com/api/v1/employees
2. 연결 확인 및 연결에 걸린 시간 확인
3. response status code 확인
4. JSON 데이터 처리 및 출력 (org.json.simple 활용)
# url 응답오류 발생시 json 파일로 저장 후 데이터 처리하는 경우 추가
# org.json.simple 활용
라이브러리 classpath에 추가
이클립스 기준 > 프로젝트 폴더 우클릭 > Properties > Java Build Path > Libraries Tab > Add External JARs... > 추가
[이클립스(Eclipse)] 외부 라이브러리(jar) 추가
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Paths; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonParseTest { // get elapsed time of Connection private static HttpURLConnection testHttpUrlConnection() throws MalformedURLException, IOException { long startTime = System.currentTimeMillis(); URL url = new URL("http://dummy.restapiexample.com/api/v1/employees"); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); long endTime = System.currentTimeMillis(); int statusCode = httpConn.getResponseCode(); String pf = (statusCode == 200) ? "success" : "fail"; System.out.println("1. connection " + pf + " in " + (endTime - startTime) + " millisecond"); System.out.println("2. Response code: " + statusCode); return httpConn; } // get response code from HttpUrlConnection private static int getResponseStatus() throws MalformedURLException, IOException { URL url = new URL("http://dummy.restapiexample.com/api/v1/employees"); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); return responseCode; } // handle JSON data and get JSON string private static String getJsonObjectString(BufferedReader br) throws MalformedURLException, IOException, ParseException { JSONParser jsonPar = new JSONParser(); JSONObject jsonObj = (JSONObject) jsonPar.parse(br); JSONObject outputJsonObj = new JSONObject(); outputJsonObj.put("status", jsonObj.get("status").toString()); outputJsonObj.put("data", ((JSONArray) jsonObj.get("data")).get(0)); outputJsonObj.put("message", jsonObj.get("message")); String outputString = outputJsonObj.toJSONString(); return outputString; } // get JSON string from json file private static String getJsonObjectStringFromFile() throws MalformedURLException, IOException, ParseException { System.out.println("\nRead from json file instead!!"); String currentPath = Paths.get(".").normalize().toString(); FileReader fr = new FileReader(currentPath + ".\\employees.json"); BufferedReader br = new BufferedReader(fr); String outputString = getJsonObjectString(br); return outputString; } // main method public static void main(String[] args) throws MalformedURLException, IOException, ParseException { HttpURLConnection httpConn = testHttpUrlConnection(); int statusCode = getResponseStatus(); String res = null; if (statusCode == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); res = getJsonObjectString(br); } else { res = getJsonObjectStringFromFile(); } System.out.println("result string: " + res); } } |
응답 성공할 경우
응답 없는 경우 json파일 읽기
반응형