maven 을 사용하는 경우 pom.xml 파일에 다음의 의존성을 추가한다.
commons-io commons-io 2.5 org.apache.tika tika-core 1.22
이미지 파일은 임시파일을 생성하고 URL 연결을 통하여 읽어 드린 스트림을 저장하는 방식으로 구현하였다.
/** 예제 **/
package tests;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.tika.Tika;
public class DownloadImageFromUrlTest {
public static void main(String args[]){
try {
// 다운로드를 위한 이미지 URL 정보
URL url = new URL("https://...");
File image = readFileFromUrl( url );
String contentType = getContentType(image);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* get content type from file.
* @param image
* @return
*/
public static String getContentType(File image) {
String contentType = null;
Tika tika = new Tika();
try {
contentType = tika.detect(image);
} catch (IOException e) {
contentType = null;
}
return contentType;
}
/**
* read image file from url.
* @param imageUrl
* @return
* @throws IOException
*/
public static File readFileFromUrl(URL imageUrl) throws IOException {
File temp = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
temp.deleteOnExit();
FileUtils.copyURLToFile(imageUrl, temp);
return temp;
}
}
위의 코드를 사용하는 경우 403 Forbidden 오류가 발생하는 경우가 많은데 이는 해당 웹 사이트에서 프로그램을 통한 접근을 차단하기 조치가 되어 있는 것으로 추측된다.
이경우는 URL 요청시 웹 브라우저에서 접근하는 것과 유사하게 요청 헤더에 USER_AGENT 값을 추가하여 해결할 수 있다.
/** 예제 **/
package tests;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
public class DownloadImageFromUrlTest {
public static void main(String args[]){
try {
// 다운로드를 위한 이미지 URL 정보
URL url = new URL("https://...");
File image = readFileFromUrl( url );
String contentType = getContentType(image);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* get content type from file.
* @param image
* @return
*/
public static String getContentType(File image) {
String contentType = null;
Tika tika = new Tika();
try {
contentType = tika.detect(image);
} catch (IOException e) {
contentType = null;
}
return contentType;
}
/**
* read image file from url.
* @param imageUrl
* @return
* @throws IOException
*/
public static File readFileFromUrl(URL url) throws Exception {
InputStream inputStream = null;
try {
String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";
URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
inputStream = con.getInputStream();
File temp = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
FileUtils.copyToFile( inputStream, temp );
return temp;
}finally {
IOUtils.closeQuietly(inputStream);
}
}
}
위의 코드를 적용하면 대부분의 사이트에서 이미지를 다운로드가 가능한 것으로 확인되었다.
다만 추가적인 보안 조치가 있는 경우는 동작하지 않을 수 있다.
댓글 없음:
댓글 쓰기