The following is the complete code.
Copy codeThe Code is as follows:
Package cn. searchphoto. util;
Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. URL;
Import java.net. URLConnection;
Import java.util.zip. GZIPInputStream;
/**
* Download images from a remote website and set Referer to anti-leeching.
*
* @ Author JAVA century network (java2000.net, laozizhu.com)
*/
Public class ImageDownloader {
/**
* Download an object to a specified location
* @ Param imgurl download connection
* @ Param f target file
* @ Return: The file is returned successfully, and null is returned if a failure occurs.
*/
Public static File download (String imgurl, File f ){
Try {
URL url = new URL (imgurl );
URLConnection con = url. openConnection ();
Int index = imgurl. indexOf ("/", 10 );
Con. setRequestProperty ("Host", index =-1? Imgurl. substring (7): imgurl. substring (7, index ));
Con. setRequestProperty ("Referer", imgurl );
InputStream is = con. getInputStream ();
If (con. getContentEncoding ()! = Null & con. getContentEncoding (). inclusignorecase ("gzip ")){
Is = new GZIPInputStream (con. getInputStream ());
}
Byte [] bs = new byte [1024];
Int len =-1;
OutputStream OS = new FileOutputStream (f );
Try {
While (len = is. read (bs ))! =-1 ){
OS. write (bs, 0, len );
}
} Finally {
Try {
OS. close ();
} Catch (Exception ex ){}
Try {
Is. close ();
} Catch (Exception ex ){}
}
Return f;
} Catch (Exception ex ){
Ex. printStackTrace ();
Return null;
}
}
}