程序员

Java 通过设置Referer反盗链

作者:admin 2021-07-10 我要评论

下面是完整的代码。 复制代码 代码如下: package cn.searchphoto.util; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; i...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
下面是完整的代码。
复制代码 代码如下:

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

本文转载自网络,原文链接:https://m.jb51.net/article/19047.htm

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • Java 通过设置Referer反盗链

    Java 通过设置Referer反盗链

  • java session出现的错误

    java session出现的错误

  • ASP生成伪参数程序设计技巧

    ASP生成伪参数程序设计技巧

  • asp中使用mysql数据库的注意实现

    asp中使用mysql数据库的注意实现

腾讯云代理商
精彩导读
海外云服务器
热门资讯
腾讯云代理商