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

JSP
用JSP实现的一个日历程序
JSP生成jpeg图片用于投票
按IE后退按钮时让JSP不读缓存
JSP简介
Tomcat+Jsp环境下的中文问题
JSP技术生成动态web页面
在JSP中访问MS SQL Server数据库
从jsp发送动态图像
JSP/Servlet 中的汉字编码问题
困扰JSP的一些问题与解决方法
高效的jsp分页查询
JSP动态输出Excel及中文乱码的解决
JavaBean实现多文件上传的两种方法
加快JDBC设计中JSP访问数据库
将JSP在内存生成的图片显示到页面
[JAVA]十四种Java开发工具点评
JSP/Servlet应用程序优化八法
初学java常用开发工具介绍
JSP连接SQL Server 2000系统配置
win2000server IIS和tomcat5多站点配置

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


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