JAVA - Download PDF file from Webserver
Posted
by
Augusto Picciani
on Stack Overflow
See other posts from Stack Overflow
or by Augusto Picciani
Published on 2011-11-17T17:47:48Z
Indexed on
2011/11/17
17:50 UTC
Read the original article
Hit count: 302
I need to download a pdf file from a webserver to my pc and save it locally.
I used Httpclient to connect to webserver and get the content body:
HttpEntity entity=response.getEntity();
InputStream in=entity.getContent();
String stream = CharStreams.toString(new InputStreamReader(in));
int size=stream.length();
System.out.println("stringa html page LENGTH:"+stream.length());
System.out.println(stream);
SaveToFile(stream);
Then i save content in a file:
//check CRLF (i don't know if i need to to this)
String[] fix=stream.split("\r\n");
File file=new File("C:\\Users\\augusto\\Desktop\\progetti web\\test\\test2.pdf");
PrintWriter out = new PrintWriter(new FileWriter(file));
for (int i = 0; i < fix.length; i++) {
out.print(fix[i]);
out.print("\n");
}
out.close();
I also tried to save a String content to file directly:
OutputStream out=new FileOutputStream("pathPdfFile");
out.write(stream.getBytes());
out.close();
But the result is always the same: I can open pdf file but i can see white pages only. Does the mistake is around pdf stream and endstream charset encoding? Does pdf content between stream and endStream need to be manipulate in some others way?
© Stack Overflow or respective owner