2013-10-11 70 views
2

我审阅了关于这个论坛所有类似questions(不仅如此!),并已经尝试了所有的这些方法却仍然无法以编程下载测试文件:http://pdfobject.com/markup/examples/full-browser-window.html如何从.html扩展名的网页下载PDF文件programmatticaly?

以下为direct link的测试文件我正在尝试下载。这是一个开放访问的测试pdf文件,因此任何人都可以使用它来测试下载方法。

如何下载这个特定的文件,使其具有pdf扩展名?

+1

你可以做那些答案说的。告诉我们你试过的是什么以及它失败的原因。 –

+0

你有什么具体问题?这听起来像你只是说“它没有工作” - 你是否得到错误?崩溃?别的东西? – Krease

+0

谢谢你的回复。我尝试了所有我发现的方法,但总会有一个错误,例如'contentLenght = -1'。我会用我的一个尝试的代码更新我的问题,但是它会占用很多空间。这里是更新(见上) – CHEBURASHKA

回答

4

对于下载文件时,也许你可以尝试这样的事:

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 
import java.net.URLConnection; 

public final class FileDownloader { 

    private FileDownloader(){} 

    public static void main(String args[]) throws IOException{ 
     download("http://pdfobject.com/pdf/sample.pdf", new File("sample.pdf")); 
    } 

    public static void download(final String url, final File destination) throws IOException { 
     final URLConnection connection = new URL(url).openConnection(); 
     connection.setConnectTimeout(60000); 
     connection.setReadTimeout(60000); 
     connection.addRequestProperty("User-Agent", "Mozilla/5.0"); 
     final FileOutputStream output = new FileOutputStream(destination, false); 
     final byte[] buffer = new byte[2048]; 
     int read; 
     final InputStream input = connection.getInputStream(); 
     while((read = input.read(buffer)) > -1) 
      output.write(buffer, 0, read); 
     output.flush(); 
     output.close(); 
     input.close(); 
    } 
} 
+0

+1非常感谢你......我不知道这种方法,但它给出了与其他方法相同类型的错误:“尽管文件被保存,已被破坏,无法打开” – CHEBURASHKA

+0

这很奇怪,因为它适用于我:http://puu.sh/4N0S6.png也许您的PDF阅读器已损坏。 –

+0

你很可能是正确的......你会不会包含'import ...'行...也许我有困惑的事情谢谢 – CHEBURASHKA

1

让我给你一个更短的解决方案,它带有一个库调用JSoup,这BalusC经常使用他的答案。

//Get the response 
Response response=Jsoup.connect(location).ignoreContentType(true).execute(); 

//Save the file 
FileOutputStream out = new FileOutputStream(new File(outputFolder + name)); 
out.write(response.bodyAsBytes()); 
out.close(); 

好了,你现在一定已经猜到了,response.body()就是该PDF。你可以用这段代码下载任何二进制文件。

+0

非常感谢。我会尝试这个解决方案+50 – CHEBURASHKA

相关问题