FileUtils.copyUrlToFile is not working
Asked Answered
A

1

9

I have fairly basic question i'm trying to download a PDF from this URL using java:

http://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True

here is my code "very basic":

public class Main {

private static final String PATH = "C:\\project\\DownloadTest\\src\\main\\resources\\tmp\\";
private static final String FILENAME = "data.pdf";
private static final String SvDPDFURL = "http://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True";

public static void main(String[] args) throws Exception{
    File file = new File(PATH + FILENAME);
    URL url = new URL(SvDPDFURL);
    FileUtils.copyURLToFile(url, file);
 }
}

the problem is that file is empty, what i'm i doing wrong.

Androecium answered 30/7, 2014 at 8:10 Comment(9)
why do you have HTTP parameters on the end of the URL?Drunkometer
@ScaryWombat What's wrong with HTTP parameters?Shig
I did not say that anything was wrong with it.Drunkometer
Have you tried the version FileUtils.copyURLToFile(URL, File, int, int) which allows you to specify timeouts etcConfirmation
cant really answer why the URL parameter is there, this Isn't it my site (the site belongs to Sweden´s third largest newspaper). JamesB could you explain how the timeout works ?Androecium
if your system is *nix just call wgetSwipe
ensure that a read-only 0 byte file does not previously existDrunkometer
what does Du har ej access mean?Drunkometer
"Du har ej access" means that "you do not have access"Androecium
S
2

Just make it https instead of http.

https://kundservice.svd.se/ui/templates/HttpHandler/PDFTidningen/PDFTidningen.ashx?date=2014-07-27&file=SVD_D_BILAGA_2014-07-27.pdf&mac=92267fcd3c75feff13154ba66870a523&free=True

It is happening because there is a redirect when you hit the url. It redirects to https. Browsers get the response and the response code is 302 then redirects to the given url but the FileUtility can not handle that.

To confirm use firebug or chrome developers tool by hitting F12 and go to Network tab.

Shauna answered 30/7, 2014 at 9:5 Comment(1)
I think you should change your questions title to something generic like, FileUtils.copyUrlToFile is not working or 0 size file.Shauna

© 2022 - 2024 — McMap. All rights reserved.