有图片的地址,如:http://i2.pixiv.net/img-original/img/201...
还有登陆后获取的cooikes:Connection cookies(Map<String, String> cookies);
登陆和获取cooikes以及解析页面是使用的jsoup。
但是需要登陆后才能获取,使用以下代码:
private void downloadImg(String imgURL) throws MalformedURLException, IOException {
URL url = new URL(imgURL);
URLConnection uc = url.openConnection();
InputStream is = uc.getInputStream();
File file = new File("D:\\pixiv");
FileOutputStream out = new FileOutputStream(file);
int i = 0;
while ((i = is.read()) != -1) {
out.write(i);
}
is.close();
}
只能下载不需要登陆的页面的图片。
要如何使用jsoup带cooikes来从网站下载图片
ringa_lee2017-04-17 17:43:15
問題已解決,使用Firebug抓取瀏覽器中瀏覽圖片時發送的請求包然後再根據其格式,使用URLConnection構造發送帶cookies的請求包即可。 就是對於大於1M的圖片下載速度太慢了。
/**
* 下载图片从URL
*
* @param img 图片对象
* @param imgFile 代写入文件对象
* @throws MalformedURLException 获取URL异常
* @throws IOException URLConnection获取异常
*/
public void downloadImg(Img img, File imgFile) throws MalformedURLException, IOException {
URL url = new URL(img.getUrl());
URLConnection uc = url.openConnection();
uc.setConnectTimeout(Setting._Download_Img_TimeOut); // 设置下载图片超时时间
uc.setRequestProperty("accept", "image/png,image/*;q=0.8,*/*;q=0.5");
uc.setRequestProperty("accept-encoding", "gzip, deflate");
uc.setRequestProperty("accept-language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
uc.setRequestProperty("connection", "keep-alive");
uc.setRequestProperty("cookie", PixivLogin.userCookies.toString());//这里是cookie部分
uc.setRequestProperty("dnt", "1");
uc.setRequestProperty("host", "i2.pixiv.net");
uc.setRequestProperty("user-agent", Setting._DownLoadImgClient_UserAgent);
uc.setDoInput(true);
uc.setDoOutput(true);
System.out.println("图片获取成功");
System.out.println("开始写入硬盘");
InputStream is = uc.getInputStream();
FileOutputStream out = new FileOutputStream(imgFile);
//BufferedOutputStream bout = new BufferedOutputStream(out);
int i = 0;
while ((i = is.read()) != -1) {
out.write(i);
}
is.close();
System.out.println(img.getName() + "写入完毕 " + imgFile.length());
}
ringa_lee2017-04-17 17:43:15
不管你用什麼解析HTML,唯一確定你登入的就是http請求中的cookie,所以你可以先發生登入請求,從http res拿到cookie,之後再將cookie設定到下次http請求中,就完成了瀏覽器保持cookie的操作,需要登入的資源資料就可以下載了
PHP中文网2017-04-17 17:43:15
提取img src後,如果用URLConnection 下載圖片有沒有權限,看下網站中有沒有session_id之類的東西,總之就是找出用戶登入的標識,在img src中帶上些標識