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

JSP
java设计模式之Memento
java设计模式之Facade(外观)
JSP如何与EJB SessionBean通讯
通用上载组件的原理及实现
最佳实践:有状态会话 bean运行结束时应及时被显式删除
jsp预编译工具
利用javabean轻松实现对数据库的连接、查询以及增删改--使用范例
利用javabean轻松实现对数据库的连接、查询以及增删改
Redhat下安装Tomcat
用VisualAge for Java开发企业级bean
WebLogic初步研究
一个实现排列和组合的JavaBean
汉字问题深入谈-- 关于JAVA的中文问题
什么是 Enterprise JavaBeans 组件?(三)
Java的内存泄漏
JSP中SQL数据库编程技术
JSP中的字符替换函数 str_replace()实现
JSP开发工具的选择
Jsp分页实例代码
JSP标签快速检索

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 72 ::
收藏到网摘: 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;
}
}
}