当前位置: 首页 > 图文教程 > 网络编程 > JSP > Java 通过设置Referer反盗链

JSP
一个可以防止刷新的JSP计数器
jsp文件操作之写入篇
jsp文件操作之追加篇
jsp文件操作之读取篇
六、访问CGI变量
七、HTTP应答状态
八、设置HTTP应答头
十、会话状态
十二、脚本元素、指令和预定义变量
十三、JSP动作
五、读取HTTP请求头
JSP入门教程(1)
九、处理Cookie
JSP入门教程(3)
JSP入门教程(4)
四、处理表单数据
JSP在Linux下的安装
在 Linux 上安装Apache+ApacheJServ+JSP
在Windows/NT上建立JSP环境
Java Servlet和JSP教程

JSP 中的 Java 通过设置Referer反盗链


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 104 ::
收藏到网摘: n/a

以前写过通过URLConnection下载图片等网络资源的代码,不过发现象新浪等网站,都不允许直接连接,所以增强了代码,通过模拟仿造referer来实现下载。 下面是完整的代码。
复制代码 代码如下:

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;
}
}
}