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