国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JSP > 正文

Java 通過設置Referer反盜鏈

2024-09-05 00:21:17
字體:
供稿:網(wǎng)友
以前寫過通過URLConnection下載圖片等網(wǎng)絡資源的代碼,不過發(fā)現(xiàn)象新浪等網(wǎng)站,都不允許直接連接,所以增強了代碼,通過模擬仿造referer來實現(xiàn)下載。

下面是完整的代碼。

復制代碼 代碼如下:


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;
/**
* 下載遠程網(wǎng)站的圖片,通過設置Referer反反盜鏈。
*
* @author JAVA世紀網(wǎng)(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;
}
}
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 商河县| 大理市| 罗田县| 呈贡县| 彰化县| 八宿县| 安阳市| 喀什市| 南汇区| 剑川县| 仁怀市| 万荣县| 象州县| 崇左市| 东莞市| 崇州市| 揭阳市| 鄂伦春自治旗| 廉江市| 茌平县| 疏附县| 东源县| 宜兰市| 商水县| 抚顺市| 高阳县| 鄂伦春自治旗| 卓尼县| 慈溪市| 文成县| 宁海县| 永和县| 滕州市| 田林县| 湘潭市| 长海县| 青州市| 祁东县| 改则县| 天津市| 穆棱市|