简体   繁体   中英

Error downloading file from a given URL

I am trying to download the given URL: http://www.addic7ed.com/original/9521/7

but when i try to download the file using my Java Code:

URL url = new URL("http://www.addic7ed.com/original/9521/7");
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream("abc.srt"); 
fos.getChannel().transferFrom(rbc, 0, 1 << 24);

The html page gets downloaded whereas the file to be downloaded should be a .srt extension file.

But when I try to download the above link using Internet Download Manager the file gets downloaded.

IDM converts the above given URL into http://www.addic7ed.com/srtcache/Supernatural/Supernatural%20-%2004x06%20-%20Yellow%20Fever.720p%20CTU.English.orig.Addic7ed.com.srt

So my question is how to achieve this in JAVA...?? Are there any API available to achieve this.

Have you looked at the HTML file? I suspect that it is actually an error page from the server, and that it contains clues about what is actually going on.

Here are some possibilities:

  • Maybe you need to supply authentication credentials.

  • Maybe the server is sending a redirect (3xx) response, and that the client side is not performing the redirect.

  • Maybe you need to set some extra headers to make the server realize that it should not turn the response as HTML. For example, an Accept header.

But note that the details will depend on the server that you are trying to talk to.


If I was trying to download files programmatically in Java, I would either use HttpUrlConnection or the Apache HttpClient libraries. Both will give you more control over the download process than simply using URL.openStream()

This is probably because the http response from http://www.addic7ed.com/original/9521/7 is a 302 redirect which your java code is not correctly handling. IDM correctly handles the redirect. A great tool to use if you are on a *nix based systme, or have cygwin installed on windows is curl.

curl -v http://myurl

will display all the http traffic information (request/response)

你试过了吗?

URL url = new URL("http://www.addic7ed.com/original/9521/7");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM