欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 通过设置Referer反盗链

程序员文章站 2023-11-29 08:06:40
下面是完整的代码。复制代码 代码如下:package cn.searchphoto.util; import java.io.file; import java.io.fi...
下面是完整的代码。
复制代码 代码如下:

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;
/**
* 下载远程网站的图片,通过设置referer反反盗链。
*
* @author java世纪网(java2000.net, laozizhu.com)
*/
public class imagedownloader {
/**
* 下载文件到指定位置
* @param imgurl 下载连接
* @param f 目标文件
* @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;
}
}
}