url返回json数据结构
通过http请求获取路径信息并下载
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>(8);
// for (int i = 41; i <= 80; i++) {
map.put("index", 1);
map.put("_ts_", System.currentTimeMillis());
map.put("size", 5);
System.out.println("第" + 1 + "页");
String result = HttpURLConnectionUtil.get("https://XXXX/front/painter/list", map);
JSONObject jsonObject = JSONObject.parseObject(result);
//获取返回数据
Map<String, Object> map1 = (Map<String, Object>) jsonObject.get("data");
List<Datas> datas = (List<Datas>) map1.get("datas");
for (Object data : datas) {
String jsonString = JSON.toJSONString(data);
JSONObject datasJson = JSONObject.parseObject(jsonString);
String name = datasJson.get("name").toString();
//创建文件夹 包含子级目录
File file = new File("D:\\patin\\" + name);
file.mkdirs();
String filePath = file.getPath();
System.out.println("文件夹路径" + filePath);
List<WorksList> worksList = (List<WorksList>) datasJson.get("worksList");
for (Object pictVo : worksList) {
String pictVoJson = JSON.toJSONString(pictVo);
JSONObject pict = JSONObject.parseObject(pictVoJson);
String coverImage = pict.get("coverImage").toString();
JSONObject jsonObject1 = JSONObject.parseObject(coverImage);
//获取文件名称
String path = jsonObject1.getString("path");
//拼接域名
String url = "https://img2.huashi6.com/" + path;
String fileName = url.substring(url.lastIndexOf("/") + 1);
downloadPicture(url, filePath + "/" + fileName);
System.out.println(fileName);
}
}
// }
}
下载方法
private static void downloadPicture(String urlList, String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
//设置缓冲区字节大小
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
//关闭流
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}