첨부파일 형식이 아닌 일반 이미지를 다운받아야 해서
아래와 같은 함수를 만들었다.
이미지주소, 다운받을 경로, 이미지파일 이름을 매개변수로 넘겨주고
최종 저장된 이미지 파일(확장자포함)를 반환하는 함수이다.
protected String downloadImage(String imgUrl, String downDir, String name) {
try {
URL url = new URL(imgUrl);
URLConnection uc = url.openConnection();
InputStream is = new BufferedInputStream(uc.getInputStream());
FileOutputStream fos = new FileOutputStream(downDir+File.separator+name+".jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while((bytesRead = is.read(buffer)) != -1 ) {
fos.write(buffer, 0, bytesRead);
}
is.close();
fos.close();
System.out.println("이미지 다운로드 성공");
} catch (Exception e) {
e.printStackTrace();
}
return name+".jpg";
}
그런데 자꾸 에러가 떴음. 이미지 경로에 접근할 수 없다는.
구래서
URL url = new URL(imgUrl);
URLConnection uc = url.openConnection();
// 추가
uc.setRequestProperty("User-Agent", "Mozilla/5.0 블라블라 자신의 user-Agent");
InputStream is = new BufferedInputStream(uc.getInputStream());
FileOutputStream fos = new FileOutputStream(downDir+File.separator+name+".jpg");
중간에
uc.setRequestProperty("User-Agent", "Mozilla/5.0 (어쩌구)");
추가하니 잘 됨~~
자신의 user-agent를 확인하는 방법은
F12 누르고 console창에서
navigator.userAgent 치면 나옴!
참조사이트
java.io.IOException: Server returned HTTP response code: 403 for URL
I want to download the mp3 file from url : "http://upload13.music.qzone.soso.com/30671794.mp3", i always got java.io.IOException: Server returned HTTP response code: 403 for URL. But it's ok when o...
stackoverflow.com