PCR 검사 가능 병원 조회 - ex03
세 번째 테스트 목적 : totalCount개 다운로드 받기
전략
(1) 1개의 데이터 다운로드 -> totalCount 확인
(2) totalCount만큼 다운로드 -> 파싱 -> 검증(item 사이즈)
1. URL 주소 만들기 -> totalCount 확인용
// 1. URL 주소 만들기 - totalCount 확인용
StringBuffer totalCountCheckURL = new StringBuffer();
totalCountCheckURL.append("http://apis.data.go.kr/B551182/rprtHospService/getRprtHospService");
totalCountCheckURL.append("?serviceKey="); // 서비스 키
totalCountCheckURL.append("서비스키%3D%3D");
totalCountCheckURL.append("&pageNo="); // 몇번째 페이지 인지
totalCountCheckURL.append("1");
totalCountCheckURL.append("&numOfRows=");
totalCountCheckURL.append("2"); // totalCount 체크만 할 것이기 때문에 2개만 받아도 된다.
// 1개만 받으면 List를 Object로 받기 때문에 2개를 받는다.
totalCountCheckURL.append("&_type=");
totalCountCheckURL.append("json"); // 데이터 포맷은 JSON
분명 1개의 데이터만 받아와서
totalCount의 개수만 확인하면 되는데
2개의 데이터를 받아오는 이유는 무엇일까?
totalCountCheckURL.append("&numOfRows=");
totalCountCheckURL.append("2");
1개의 데이터를 받아오면
아래와 같은 오류가 발생한다.
파싱을 하기 위해 만든 Dto에
Item을 List 타입으로 선언했었다.
리스트 타입의 데이터가 들어올 줄 알았는데
하나의 데이터만 들어와서
리스트가 아닌 오브젝트 타입이 들어왔다고 인식하는 것이다.
그렇기 때문에 데이터를 2개 받아오는 것이다.
2. 다운로드 받기 -> totalCount 확인용
URL urlTemp = new URL(totalCountCheckURL.toString());
HttpURLConnection connTemp = (HttpURLConnection) urlTemp.openConnection();
BufferedReader brTemp = new BufferedReader(
new InputStreamReader(connTemp.getInputStream(), "utf-8"));
StringBuffer sbTotalCountCheck = new StringBuffer(); // 통신결과 모아두기
while (true) {
String input = brTemp.readLine();
// 버퍼가 비었을 때 break
if (input == null) {
break;
}
sbTotalCountCheck.append(input);
}
3. 검증 -> totalCountCheck
System.out.println(sbTotalCountCheck.toString());
4. 파싱
Gson gsonTemp = new Gson();
ResponseDto totalCountCheckDto = gsonTemp.fromJson(sbTotalCountCheck.toString(), ResponseDto.class);
5. totalCount 담기
정상적으로 파싱이 끝났으니
우리가 원하는 정보만 뽑아오자.
// 5. totalCount 담기
int totalCount = totalCountCheckDto.getResponse().getBody().getTotalCount();
System.out.println("totalCount : " + totalCount);
6. 전체 데이터 다운로드 받기(totalCount)
(1) URL 주소 만들기
이제 위에서 했던 과정을 똑같이 반복해줄 것이다.
단, numOfRows의 개수만 totalCount로 바꿔서!!
// (1) URL 주소 만들기
StringBuffer sbURL = new StringBuffer();
sbURL.append("http://apis.data.go.kr/B551182/rprtHospService/getRprtHospService");
sbURL.append("?serviceKey="); // 서비스 키
sbURL.append("서비스키%3D%3D");
sbURL.append("&pageNo="); // 몇번째 페이지 인지
sbURL.append("1");
sbURL.append("&numOfRows=");
sbURL.append(totalCount);
sbURL.append("&_type=");
sbURL.append("json"); // 데이터 포맷은 JSON
(2) 다운로드 받기
// (2) 다운로드 받기 - totalCount 확인용
URL url = new URL(sbURL.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer(); // 통신결과 모아두기
while (true) {
String input = br.readLine();
// 버퍼가 비었을 때 break
if (input == null) {
break;
}
sb.append(input);
}
(3) 파싱
// (3) 파싱
Gson gson = new Gson();
ResponseDto responseDto = gson.fromJson(sb.toString(), ResponseDto.class);
7. 검증
마지막으로 totalCount개만큼 받아온
Item의 크기가 totalCount와 같은지 검증해보자.
// 7. 사이즈 검증
if (responseDto.getResponse().getBody().getItems().getItem().size() == totalCount) {
System.out.println("성공 ~~~~~~~");
}
package site.metacoding.hospapp.ex03;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
// 테스트 주도 개발!!
// 목적 : 5653개 다운로드 받기
// 전략 : (1) 다운로드 1번 -> totalCount 확인
// (2) totalCount만큼 다운로드 - 파싱 - 검증(item 사이즈)
public class AllDownloadTest {
public static void main(String[] args) {
// 1. URL 주소 만들기 - totalCount 확인용
StringBuffer totalCountCheckURL = new StringBuffer();
totalCountCheckURL.append("http://apis.data.go.kr/B551182/rprtHospService/getRprtHospService");
totalCountCheckURL.append("?serviceKey="); // 서비스 키
totalCountCheckURL.append("서비스키%3D%3D");
totalCountCheckURL.append("&pageNo="); // 몇번째 페이지 인지
totalCountCheckURL.append("1");
totalCountCheckURL.append("&numOfRows=");
totalCountCheckURL.append("2"); // totalCount 체크만 할 것이기 때문에 2개만 받아도 된다.
// 1개만 받으면 List를 Object로 받기 때문에 2개를 받는다.
totalCountCheckURL.append("&_type=");
totalCountCheckURL.append("json"); // 데이터 포맷은 JSON
// 2. 다운로드 받기 - totalCount 확인용
try {
URL urlTemp = new URL(totalCountCheckURL.toString());
HttpURLConnection connTemp = (HttpURLConnection) urlTemp.openConnection();
BufferedReader brTemp = new BufferedReader(
new InputStreamReader(connTemp.getInputStream(), "utf-8"));
StringBuffer sbTotalCountCheck = new StringBuffer(); // 통신결과 모아두기
while (true) {
String input = brTemp.readLine();
// 버퍼가 비었을 때 break
if (input == null) {
break;
}
sbTotalCountCheck.append(input);
}
// 3. 검증 - totalCountCheck
System.out.println(sbTotalCountCheck.toString());
// 4. 파싱
// 결과를 1개만 받아오면 리스트 타입도 중괄호로 받아오기 때문에 파싱 오류 발생
Gson gsonTemp = new Gson();
ResponseDto totalCountCheckDto = gsonTemp.fromJson(sbTotalCountCheck.toString(), ResponseDto.class);
// 5. totalCount 담기
int totalCount = totalCountCheckDto.getResponse().getBody().getTotalCount();
System.out.println("totalCount : " + totalCount);
// 6. 전체 데이터 받기(totalCount)
// (1) URL 주소 만들기
StringBuffer sbURL = new StringBuffer();
sbURL.append("http://apis.data.go.kr/B551182/rprtHospService/getRprtHospService");
sbURL.append("?serviceKey="); // 서비스 키
sbURL.append("서비스키%3D%3D");
sbURL.append("&pageNo="); // 몇번째 페이지 인지
sbURL.append("1");
sbURL.append("&numOfRows=");
sbURL.append(totalCount); // totalCount 체크만 할 것이기 때문에 2개만 받아도 된다.
// 1개만 받으면 List를 Object로 받기 때문에 2개를 받는다.
sbURL.append("&_type=");
sbURL.append("json"); // 데이터 포맷은 JSON
// (2) 다운로드 받기 - totalCount 확인용
URL url = new URL(sbURL.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf-8"));
StringBuffer sb = new StringBuffer(); // 통신결과 모아두기
while (true) {
String input = br.readLine();
// 버퍼가 비었을 때 break
if (input == null) {
break;
}
sb.append(input);
}
// (3) 파싱
// 결과를 1개만 받아오면 리스트 타입도 중괄호로 받아오기 때문에 파싱 오류 발생
Gson gson = new Gson();
ResponseDto responseDto = gson.fromJson(sb.toString(), ResponseDto.class);
// 7. 사이즈 검증
if (responseDto.getResponse().getBody().getItems().getItem().size() == totalCount) {
System.out.println("성공 ~~~~~~~");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
[출처]
https://cafe.naver.com/metacoding
메타 코딩 유튜브
https://www.youtube.com/c/%EB%A9%94%ED%83%80%EC%BD%94%EB%94%A9