手机
当前位置:查字典教程网 >编程开发 >JSP教程 >Java 通过设置Referer反盗链
Java 通过设置Referer反盗链
摘要:下面是完整的代码。复制代码代码如下:packagecn.searchphoto.util;importjava.io.File;import...

下面是完整的代码。

复制代码 代码如下:

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;

}

}

}

【Java 通过设置Referer反盗链】相关文章:

JSP隐式对象和MVC设计模式

JSP由浅入深(1)—— 熟悉JSP服务器

JSP中的字符替换函数 str_replace() 实现!

struts2 spring整合fieldError问题

Java源码分析:深入探讨Iterator模式

指南:想成为一个JSP网站程序员吗?

JSP中include指令和include行为的区别

二、设置开发、运行环境

Java for循环语句使用

JSP安全性初探

精品推荐
分类导航