march alex's blog
          hello,I am march alex
          posts - 52,comments - 7,trackbacks - 0
          <2015年3月>
          22232425262728
          1234567
          891011121314
          15161718192021
          22232425262728
          2930311234

          常用鏈接

          留言簿

          隨筆分類

          隨筆檔案

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          之前我寫過獲得tmall上qfour某單品頁上第一張圖片的程序
          這次我又在qfour上面選了一個貓娘志2015春秋新款女裝顯瘦小清新碎花長袖田園連衣裙女單品頁用于獲得下面的這張圖。

          這張圖對應的url為:http://gi4.md.alicdn.com/bao/uploaded/i4/TB1aRpnHpXXXXaNXVXXXXXXXXXX_!!0-item_pic.jpg
          我寫了一個ImageDownload類,其中的download方法用于下載url對應的圖片并保存在特定的本地目錄上。代碼如下:
          import java.io.File;
          import java.io.FileOutputStream;
          import java.io.InputStream;
          import java.io.OutputStream;
          import java.net.URL;
          import java.net.URLConnection;


          public class ImageDownload {
              public static void download(String urlString, String filename) throws Exception {  

                  URL url = new URL(urlString); // 構造URL  
                  URLConnection con = url.openConnection();  // 打開鏈接
                  con.setConnectTimeout(5*1000);  //設置請求超時為5s  
                  InputStream is = con.getInputStream();  // 輸入流  
                  byte[] bs = new byte[1024];  // 1K的數據緩沖  
                  int len;  // 讀取到的數據長度  
                  int i = filename.length();
                  for(i--;i>=0 && filename.charAt(i) != '\\' && filename.charAt(i) != '/';i--);
                  String s_dir = filename.substring(0, i);
                  File dir = new File(s_dir);  // 輸出的文件流  
                  if(!dir.exists()){  
                      dir.mkdirs();  
                  }  
                  OutputStream os = new FileOutputStream(filename);  
                  // 開始讀取  
                  while ((len = is.read(bs)) != -1) {  
                    os.write(bs, 0, len);  
                  }  
                  // 完畢,關閉所有鏈接  
                  os.close();  
                  is.close();  
              }
              
              public static void main(String[] args) throws Exception {
                  download("http://gi4.md.alicdn.com/bao/uploaded/i4/TB1aRpnHpXXXXaNXVXXXXXXXXXX_!!0-item_pic.jpg", "d:\\qfour\\sample.jpg");
              }
          }  
          posted on 2015-03-08 12:33 marchalex 閱讀(1763) 評論(0)  編輯  收藏 所屬分類: java小程序
          主站蜘蛛池模板: 阜阳市| 信宜市| 广德县| 封开县| 洪泽县| 眉山市| 扎兰屯市| 安达市| 喜德县| 彰武县| 乐陵市| 砚山县| 宁远县| 元谋县| 阿尔山市| 浏阳市| 渑池县| 柳州市| 洛扎县| 清远市| 光山县| 溧水县| 通化市| 安宁市| 宁陕县| 越西县| 合江县| 盐城市| 嵩明县| 兰西县| 晴隆县| 乌兰浩特市| 大丰市| 泸州市| 齐齐哈尔市| 织金县| 灵台县| 沽源县| 平度市| 滁州市| 新丰县|