1. 程式人生 > >jsoup獲取圖片並下載

jsoup獲取圖片並下載

這裡要提一下因為是返回的圖片,所以用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();
}