package com.zhy.modules;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
* @author css
* @email 13838446429@163.com
* @date 2020年05月12日 15: 51:32
*/
public class TestGetHtml {
public static void main(String[] args) {
String str = "https://www.mayiwenku.com/FileRoot1/2018-6/18/bdd73ff1-6704-40e5-a73c-007cfa513cc3/bdd73ff1-6704-40e5-a73c-007cfa513cc3";
for (int i = 232; i > 0; i--) {
String url = str + i + ".gif";
byte[] btImg = getImageFromNetByUrl(url);
if (null != btImg && btImg.length > 0) {
String fileName = i+".jpg";
writeImageToDisk(btImg, fileName,i);
} else {
System.out.println("没有从该连接获得内容");
}
}
}
/**
* 将图片写入到磁盘
*
* @param img 图片数据流
* @param fileName 文件保存时的名称
*/
public static void writeImageToDisk(byte[] img, String fileName,int a) {
try {
File file = new File("D:\\guowang\\" + fileName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(img);
fops.flush();
fops.close();
System.out.println("图片" + a + "已经写入到C盘");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据地址获得数据的字节流
*
* @param strUrl 网络连接地址
* @return
*/
public static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 从输入流中获取数据
*
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/111123.html