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 类的简单应用...

posted on 2016-08-23 14:32  西门吃雪  阅读(13495)  评论(0编辑  收藏  举报

导航