Java by setting Referer anti hotlinking

  • 2020-05-07 20:14:30
  • OfStack

Here's the complete code.

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 remote site images through Settings Referer Anti-anti-hotlinking.  
* 
* @author JAVA Century network (java2000.net, laozizhu.com) 
*/ 
public class ImageDownloader { 
/** 
*  Download the file to the specified location  
* @param imgurl  Download link  
* @param f  The target file  
* @return  Return file on success, return on failure 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; 
} 
} 
} 

Related articles: