Here is the complete code.
Copy Code code 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 pictures of remote Web site by setting referer anti-hotlinking.
*
* @author java Century Network (java2000.net, laozizhu.com)
*/
public class Imagedownloader {
/**
* Download files to the specified location
* @param imgurl Download Connection
* @param f Target Document
* @return successfully returned the file, failed to return null
*/
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 (). Equalsignorecase ("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;
}
}
}