본문 바로가기
개발

HttpUrlConnection을 사용해 PDF 내려받기

by hxxyeoniii 2024. 2. 13.

URLConnection과 HttpURLConnection에 대해

URLConnection

> Java 애플리케이션과 URL간의 연결을 나타내는 모든 클래스들의 수퍼 클래스
->일반 URL에 대한 API를 제공

 

HttpUrlConnection

> HTTP 관련 기능에 대한 추가 지원 제공
 

 

 


-> 이 둘은 모두 추상 클래스이므로 새 인스턴스를 직접 만들 수 없다. 대신 URL 객체에서 연결을 통해 URLConnection의 인스턴스를 얻는다.
 


HttpUrlConnection을 통해 PDF 내려받기

호출 api 예시)
https:/xxxxxxxx/{document_id} : document_id를 쿼리 파라미터 형식으로 넘겨준다.
 
1. url 셋팅

String apiUrl = "https://xxxxxxxx/";
apiUrl += (String) cntrInfo.get("eform_doc_id");
url = new URL(apiUrl);

 

 


2. HttpUrlConnection 객체 생성

HttpURLConnection conn = null;
conn = (HttpURLConnection)url.openConnection();
conn.addRequestProperty("Content-Type", "application/pdf");
conn.addRequestProperty("Authorization", "Bearer " + tokenInfo.get("access_token")); // authorization 헤더 정보 추가

 

 


3. api 호출 및 응답코드 받아오기

if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { // 응답코드 200이 아닐 경우
	throw new IOException(conn.getResponseMessage());
}

 

 


4. 응답 결과 inputStream으로 받아오기

inputStream = conn.getInputStream();

 

 


5. 바이트 스트림으로 응답받은 inputStream 읽기

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 8];
            
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
	out.write(buffer, 0, len);
}

 

 


6. 새로운 빈 파일을 만들고 바이트 스트림 입력하기

File file = new File("C:/upload/test.pdf");
fileOutputStream = new FileOutputStream(file); // 빈 파일 생성
fileOutputStream.write(out.toByteArray());

 

 


7. C:/upload/test.pdf 확인


최종 코드는 아래와 같다.

public void downloadPdf(Map<String, Object> param) {
	Map<String, Object> resultMap = new HashMap<String, Object>();
        
	String apiUrl = "https://xxxxxxxx/";
		
	InputStream inputStream = null;
        URL url = null; 
        HttpURLConnection conn = null;
        File file = null;
        FileOutputStream fileOutputStream = null;
        OutputStream outputStream = null;

        try{
        	file = new File("C:/upload/test.pdf");
        	url = new URL(apiUrl);
        	
        	conn = (HttpURLConnection)url.openConnection();
        	conn.addRequestProperty("Content-Type", "application/pdf");
        	conn.addRequestProperty("Authorization", "Bearer " + tokenInfo.get("access_token"));
        	
        	if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) {
                	throw new IOException(conn.getResponseMessage());
            	}
        	
                inputStream = conn.getInputStream();

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 8];

                int len = 0;
                while((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }

		file = new File("C:/upload/test.pdf");
                fileOutputStream = new FileOutputStream(file); // 빈 파일 생성
                fileOutputStream.write(out.toByteArray());

                /*
                // inputStream에 값이 없을 때까지 모두 읽기
                while((inputStream.read(buffer)) != -1) {
                    bytesRead = inputStream.read(buffer);
                    fileOutputStream.write(buffer, 0, bytesRead); // 파일에 write
                }*/

                /*
                // 매번 api 호출을 통해 pdf를 내려받는 것이 아닌, 파일 스토리지에 저장해 사용하기 위해
                OBSMultipartFileItem fileItem = new OBSMultipartFileItem();
                FileInputStream fis = new FileInputStream(file);

                // OBSMultipartFileItem 파일 스토어 파일 생성
                fileItem.setId(UUID.randomUUID().toString());
                fileItem.setGroupId(cntrGrpCd);
                fileItem.setName(fileNm);
                fileItem.setExtension("pdf");
                fileItem.setSize(file.length());
                fileItem.setReference(null);
                fileItem.setContents(null);
                fileItem.setFile(file);
                fileItem.setMultipartFile(new MockMultipartFile(fileNm, fis));
                fileService.create(fileItem);

                cntrInfo.put("cntr_grp_cd", cntrGrpCd);
                sqlSession.update("contract.updateCntrFileHash", cntrInfo);

                if(fileOutputStream != null) {
                    fileOutputStream.flush();
                }
                */
            } catch(Exception e) {
                throw new EdocException(this.getClass().getName() + ".downloadPdf() : Exception", e.getMessage());
            } finally {
                try {
                    fileOutputStream.close();
                    inputStream.close();
                    // if(file.exists()) file.delete();
                } catch(Exception e) {
                    throw new EdocException(this.getClass().getName() + ".downloadPdf() : Exception", e.getMessage());
                }
            }
	}