Java-->利用URL類下載圖片


--> 通過get 請求訪問圖片地址,將通過服務器響應的數據(即圖片數據)存到本地文件中...

--> HttpURLConnectionUtil 工具類

package com.dragon.java.downloadpic;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionUtil {
        // 通過get請求得到讀取器響應數據的數據流
    public static InputStream getInputStreamByGet(String url) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");

            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                return inputStream;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

        // 將服務器響應的數據流存到本地文件
    public static void saveData(InputStream is, File file) {
        try (BufferedInputStream bis = new BufferedInputStream(is);
                BufferedOutputStream bos = new BufferedOutputStream(
                        new FileOutputStream(file));) {
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
                bos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

--> Test 測試類

package com.dragon.java.downloadpic;

import java.io.File;
import java.io.InputStream;

/*
 * 1. 從下面的地址下載圖片,並保存在文件中。
 http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg
 *要求:封裝相應的工具類*
 */
public class Test {
    public static void main(String[] args) {
        String url = "http://img.coocaa.com/www/attachment/forum/201602/16/085938u86ewu4l8z6flr6w.jpg";

      String[] split = url.split("\\/");
      String fileName = split[split.length - 1];
      File file = new File("f:/", fileName);

        InputStream inputStream = HttpURLConnectionUtil
                .getInputStreamByGet(url);
        HttpURLConnectionUtil.saveData(inputStream, file);
    }
}

--> URL 類的簡單應用...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM