Java implementation download PDF document from URL path to local

Source: Internet
Author: User

Package Com.cellstrain.icell.util;


import java.io.*;
import java.net.*;

Public class Downloadpdf {

/**
* Download files from the network URL
* @param urlstr
* @param fileName
* @param savepath
* @throws IOException
*/
Public static void Downloadbyurl (String urlstr,string filename,string savepath) throws ioexception{
url url = new URL (urlstr);
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
//Set timeout to 3 seconds
conn.setconnecttimeout (5*1000);
//Prevent the masking program from crawling and return 403 error
conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT; Digext) ");
//Get input stream
InputStream InputStream = Conn.getinputstream ();
//Get yourself an array
byte[] GetData = Readinputstream (InputStream);
//File Save location
file Savedir = new file (Savepath);
if (!savedir.exists ()) {
Savedir.mkdir ();
}
File File = new file (savedir+file.separator+filename);
FileOutputStream fos = new FileOutputStream (file);
Fos.write (getData);
if (fos!=null) {
fos.close ();
}
if (inputstream!=null) {
inputstream.close ();
}
System.out.println ("info:" +url+ "Download Success");

}


/**
* Get the byte array from the input stream
* @param inputstream
* @return
* @throws IOException
*/
Public Static byte[] Readinputstream (InputStream inputstream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
bytearrayoutputstream bos = new Bytearrayoutputstream ();
While (len = inputstream.read (buffer))! =-1) {
bos.write (buffer, 0, Len);
}
bos.close ();
return Bos.tobytearray ();
}

Public static void Main (string[] args) {
try{
Downloadbyurl ("Https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_ Protocol.pdf ",
" elisa.pdf", "E:/upload/protocol");
}catch (Exception e) {
//Todo:handle exception
}
}
}

Java implementation download PDF document from URL path to local

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.