打赏 jQuery火箭图标返回顶部代码

JAVA获取网络图片并保存到本地(随机图片接口)

 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.net.URL;
 7 import javax.net.ssl.HttpsURLConnection;
 8  
 9 public class FirstTest {
10  
11     public static void main(String[] args) throws Exception {
12         // TODO 自动生成的方法存根
13         
14         long start=System.currentTimeMillis();
15         System.out.println("开始");
16         
17         for(int i=1;i<=100;i++) {
18 //            double r=(0+Math.random()*10000);
19 //            System.out.println(r);
20             String url="https://source.unsplash.com/random";//一个随机图片接口
21 //            +(0+Math.random()*10000);可以在random后面加入一个随机数避免图片重复
22             getImg(url,i);
23             System.out.println("完成"+i);
24         }
25         long end=System.currentTimeMillis();
26         System.out.println("运行时间:"+(end-start)/1000+"秒");
27     
28     
29     }
30     private static void getImg(String u,int i){
31         URL url;
32         try {
33             url = new URL(u);
34             HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
35             conn.setRequestMethod("GET");
36             conn.setConnectTimeout(5*1000);
37             InputStream in = conn.getInputStream();
38             byte[] data = readInputStream(in);
39             File f = new File("C:\\Users\\Administrator\\Desktop\\img\\"+i+".jpg");
40             FileOutputStream out = new FileOutputStream(f);
41             out.write(data);
42             out.close();
43         } catch (IOException e) {
44             // TODO 自动生成的 catch 块
45             e.printStackTrace();
46         }
47     
48     }
49  
50     private static byte[] readInputStream(InputStream ins) throws IOException {
51         // TODO 自动生成的方法存根
52         ByteArrayOutputStream out = new ByteArrayOutputStream();
53         byte[] buffer = new byte[1024];
54         int len = 0;
55         while ((len = ins.read(buffer)) != -1) {
56             out.write(buffer, 0, len);
57  
58         }
59         ins.close();
60  
61         return out.toByteArray();
62     }
63  
64 }

 

posted @ 2018-07-19 20:26  浪漫De刺猬  阅读(3430)  评论(0编辑  收藏  举报