Проблема заключается в том, что я знаю, как загрузить File
из URL
, например:Загрузить файл на Java с URL-адреса 1), где вы не знаете расширение [например .jpg] или 2) перенаправляется на файл
http://i12.photobucket.com/albums/a206/zxc6/1_zps3e6rjofn.jpg
Когда речь идет о файлах, как ниже:
https://images.duckduckgo.com/iu/?u=http%3......
I га Не знаю, как его загрузить.
код, я использую для загрузки файлов с IOUtils он прекрасно работает, если расширение видно, но в случае приведенного выше примера возвращает:
java.io.IOException: Server returned HTTP response code: 500 for URL: https://images.duckduckgo.com/iu/?u=http%3A%2F%2Fimages2.fanpop.com%2Fimage%2Fphotos%2F8900000%2FFirefox-firefox-8967915-1600-1200.jpg&f=1
Даже если вы удалите &f=1
.
Код для Downloader
(Это для тестирования .... прототип):
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
public class Downloader {
private static class ProgressListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// e.getSource() gives you the object of
// DownloadCountingOutputStream
// because you set it in the overriden method, afterWrite().
System.out.println("Downloaded bytes : " + ((DownloadProgressListener) e.getSource()).getByteCount());
}
}
/**
* Main Method
*
* @param args
*/
public static void main(String[] args) {
URL dl = null;
File fl = null;
String x = null;
OutputStream os = null;
InputStream is = null;
ProgressListener progressListener = new ProgressListener();
try {
fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/image.jpg");
dl = new URL(
"https://images.duckduckgo.com/iu/?u=http%3A%2F%2Fimages2.fanpop.com%2Fimage%2Fphotos%2F8900000%2FFirefox-firefox-8967915-1600-1200.jpg&f=1");
os = new FileOutputStream(fl);
is = dl.openStream();
// http://i12.photobucket.com/albums/a206/zxc6/1_zps3e6rjofn.jpg
DownloadProgressListener dcount = new DownloadProgressListener(os);
dcount.setListener(progressListener);
URLConnection connection = dl.openConnection();
// this line give you the total length of source stream as a String.
// you may want to convert to integer and store this value to
// calculate percentage of the progression.
System.out.println("Content Length:" + connection.getHeaderField("Content-Length"));
System.out.println("Content Length with different way:" + connection.getContentType());
System.out.println("\n");
// begin transfer by writing to dcount, not os.
IOUtils.copy(is, dcount);
} catch (Exception e) {
System.out.println(e);
} finally {
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
}
}
Код для DownloadProgressListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.io.output.CountingOutputStream;
public class DownloadProgressListener extends CountingOutputStream {
private ActionListener listener = null;
public DownloadProgressListener(OutputStream out) {
super(out);
}
public void setListener(ActionListener listener) {
this.listener = listener;
}
@Override
protected void afterWrite(int n) throws IOException {
super.afterWrite(n);
if (listener != null) {
listener.actionPerformed(new ActionEvent(this, 0, null));
}
}
}
Вопрос Я прочитал, прежде чем отправлять :
1) Download file from url that doesn't end with .extension
2) http://www.mkyong.com/java/how-to-get-url-content-in-java/
3) Download file using java apache commons?
4) How to download and save a file from Internet using Java?
5) How to create file object from URL object
Это не имеет никакого отношения к расширению. – shmosel
@shmosel Вы можете исправить заголовок, если я ошибаюсь. Вот как я, хотя это. Это связано с перенаправлением? – GOXR3PLUS
Как указал шмосель, расширение не имеет значения.Проблема заключается в попытке загрузить что-то, что, вероятно, является перенаправлением или другим запросом. Я не уверен в каком-либо простом решении, но если вы посмотрите на: https://images.duckduckgo.com/iu/?u=http%3A%2F%2Fimages2.fanpop.com%2Fimage%2Fphotos%2F8900000% 2FFirefox-firefox-8967915-1600-1200.jpg & f = 1', на самом деле есть URL-адрес изображения, которое вы можете проанализировать. –