jsoup获取图片并下载

来源:互联网 发布:苹果手机快速打开数据 编辑:程序博客网 时间:2024/06/05 17:15

这里要提一下因为是返回的图片,所以用Jsoup获取的时候请求要加上

.ignoreContentType(true)


接下来先获取到图片:

private static  Connection.Response getCheckImage(String url)

{

try

{

return Jsoup.connect(url)

.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")

.header("Accept-Encoding", "gzip, deflate, br")

.header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")

.header("Connection", "keep-alive").header("Host", "s.nacao.org.cn")

.header("Referer", "https://s.nacao.org.cn/verifyYzmNew.jsp")

.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0")

.cookie("__utma", "87983578.129704192.1512630398.1512630398.1512960917.2")

.cookie("__utmc", "108799005")

.cookie("__utmz", "87983578.1512630398.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)")

.cookie("Hm_lvt_a17f93a4ef326580ad360f8b1419c389", "1512539142,1512961501")

.cookie("Hm_lpvt_a17f93a4ef326580ad360f8b1419c389", "1512961501")

.cookie("JSESSIONID", "B08B646CC225BB59232F0F54A0674EC7")

.cookie("bg7044", "1|Wi4OI|Wi4GM")

.ignoreContentType(true)

.execute();

} catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

return null;

}



接下来是保存图片的方法


public static void savaImage(byte[] img, String filePath, String fileName)
{

BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
File dir = new File(filePath);
try
{
// 判断文件目录是否存在
if (!dir.exists() && dir.isDirectory())
{
dir.mkdir();
}
file = new File(filePath + "\\" + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(img);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
if (bos != null)
{
try
{
bos.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


那么如何将这两个方法联系起来呢???

Connection.Response document = getCheckImage("https://s.nacao.org.cn/servlet/ValidateCode?time=");
byte[] img = document.bodyAsBytes();
savaImage(img,"C:\\IMG","checkImage"+i+".jpg");//后面这个参数是你存放的地址
log.info("savaImage"+i);

就是这样了。


接下来在给你们一个不用jsoup的方法


URL url1;
// 根据所给地址创建URL
try
{
url1 = new URL(url);
DataInputStream fileInputStream = new DataInputStream(url1.openStream());
@SuppressWarnings("resource")
// 创建输出流输入存放地址
FileOutputStream outputStream = new FileOutputStream("C:/Users/coder/Desktop/checkCode.jpeg");
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, length);
}


} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}


原创粉丝点击