HD

URL로 첨부파일 다운로드 본문

JAVA

URL로 첨부파일 다운로드

hunecenter 2021. 9. 1. 15:29
반응형

- 최근 DB Migration 중에 URL로 첨부파일을 땡겨오기 위해서 구현한 로직

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;
/**
 * @Class Name  : httpdownload.java
 * @Description :  http, https URL 첨부파일 다운
 * @Modification Information
 * @author HD
 * @version 1.0
 * @see
 *
 */
public class httpdownload {
	/**
	 * http, https URL 첨부파일 다운
	 * @param httpUrl 다운받을 URL
	 * @param downPath 다운받을 local path
	 * @param downName 다운파일명
	 */
	public static void httpDown(String httpUrl, String downPath, String downName) {
		FileOutputStream fos = null;
		InputStream is = null;
		
		try {
			//디렉토리 체크
			File file = new File(downPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			
			fos = new FileOutputStream(downPath+downName);
			
			System.out.println("httpUrl = "+httpUrl);
			URL url = new URL(httpUrl);
			URLConnection urlConnection = url.openConnection();
			//https
			//HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
			is = urlConnection.getInputStream();
			
			byte[] buffer = new byte[1024];
			int readBytes;
			while ((readBytes = is.read(buffer)) != -1) {
				fos.write(buffer, 0, readBytes);
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

 

반응형
Comments