java - Downloading binary file from url -
i using code download files url:
fileutils.copyurltofile(url, new file("c:/songs/newsong.mp3"));
when create url using instance, "https://mjcdn.cc/2/282676442/mjugu2fhbcatifzlzxqgqmfsaml0lm1wmw==", works fine , mp3 downloaded. however, if use url: "https://dl.jatt.link/hd.jatt.link/a0339e7c772ed44a770a3fe29e3921a8/uttzv/hummer-(mr-jatt.com).mp3", file 0kb.
i able download files both these urls within web browser. what's wrong here, , how can fix it.
i noticed difference between 2 urls:
- the first 1 gives file without redirection.
- but second 1 responds redirect (
http/1.1 302 moved temporarily
). it's special case, because it's redirect https http protocol.
browsers can follow redirects, program - reason (see below) - can't.
i suggest use http client library (e.g. apache http client or jsoup), , configure follow redirects (if don't default).
for example, jsoup, need code this:
string url = "https://dl.jatt.link/hd.jatt.link/a0339e7c772ed44a770a3fe29e3921a8/uttzv/hummer-(mr-jatt.com).mp3"; string filename = "c:/songs/newsong.mp3"; response r = jsoup.connect(url) //.followredirects(true) // follow redirects (it's default) .ignorecontenttype(true) // accept not html .maxbodysize(10*1000*1000) // accept 10m bytes (default 1m), or set 0 unlimited .execute(); // send request fileoutputstream out = new fileoutputstream(new file(filename)); out.write(r.bodyasbytes()); out.close();
update on @ejp's comment:
- i looked apache commons io's
fileutils
class on github. callsopenstream()
of receivedurl
object. openstream()
shorthandopenconnection().inputstream()
.openconnection()
returnsurlconnection
object. if there appropriate subclass protocol usedurl
, return instance of subclass. in case that'shttpsurlconnection
subclass ofhttpurlconnection
.- the followredirects option defined in
httpurlconnection
, it's indeedtrue
default:
sets whether http redirects (requests response code 3xx) should automatically followed class. true default.
- so op's approach work redirects too, seems redirection https http not handled (properly)
httpsurlconnection
. - it's case @vgr mentioned in comments below. - it's possible handle redirects manually reading
location
headerhttpsurlconnection
, use in newhttpurlconnection
. (example) (i wouldn't surprised if jsoup did same.) - i suggested jsoup because implements way handle https http redirections correctly , provides tons of useful features.
Comments
Post a Comment