根据图片地址从互联网下载图片到指定电脑指定位置

代码1(不支持https链接)

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class Test {
    public static void main(String[] args) {
        // 下载图片的地址
        String imgUrl = "https://bkimg.cdn.bcebos.com/pic/55e736d12f2eb938e8824ef3da628535e4dd6fc7?x-bce-process=image/watermark,image_d2F0ZXIvYmFpa2UxMTY=,g_7,xp_5,yp_5/format,f_auto";
        File file = null;
        FileOutputStream out = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        // 设置保存图片的文件夹路径
        File dir = new File("C:/test/img/" + new SimpleDateFormat("yyyy/MM-dd/HH").format(new Date()));
        // 如果保存图片的文件夹不存在,那就创建
        if (!dir.exists()) {
            // mkdir()只能创建1级文件夹,而mkdirs()可以创建路径中出现的所有文件夹
            dir.mkdirs();
        }
        try {
            // 第一个参数是图片存放的路径,第二个参数是图片的名称,这里我采用UUID生成图片名称
            file = new File(dir, UUID.randomUUID().toString().replace("-", "") + ".jpg");
            // 构造一个URL对象
            URL url = new URL(imgUrl);
            // 获取URLConnection对象
            conn = (HttpURLConnection) url.openConnection();
            // 设置请求方式,默认是GET
            conn.setRequestMethod("GET");
            // 限制输入流等待数据到达的时间,超时将会抛出java.net.SocketTimeoutException
            conn.setReadTimeout(3000);
            // 限制socket等待建立连接的时间,超时将会抛出java.net.SocketTimeoutException
            conn.setConnectTimeout(3000);
            // 获取输入流
            inputStream = conn.getInputStream();
            // 以流的方式输出图片
            out = new FileOutputStream(file);
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(arr)) != -1) {
                out.write(arr, 0, len);
            }
            out.flush();
            System.out.println("提醒:图片下载成功!!!\n图片保存地址:" + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 回收资源
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

代码2(支持https链接)

import com.leadal.framework.util.UUIDUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class ImgUtil {
    public static void main(String[] args) throws Exception {
        String imgUrl = "https://bkimg.cdn.bcebos.com/pic/55e736d12f2eb938e8824ef3da628535e4dd6fc7";

        File file = getImgFile(imgUrl);

        System.out.println("提醒:图片下载成功!!!\n图片保存地址:" + file.getAbsolutePath());
    }

    public static File getImgFile(String imgUrl) {
        // 创建图片对象
        File imgFile = FileUtil.createTempFile(UUIDUtil.create() + ".jpg");
        // 创建client对象
        CloseableHttpClient client = null;
        try {
            client = new DefaultSSLUtils();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 创建response对象
        CloseableHttpResponse response = null;
        // 获取输入流
        InputStream inputStream = null;
        // 文件输出流
        FileOutputStream out = null;
        try {
            // 构造一个URL对象
            URIBuilder uriBuilder = new URIBuilder(imgUrl);
            // 创建http对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 处理config设置
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = client.execute(httpGet);
            // 获取输入流
            inputStream = response.getEntity().getContent();
            // 以流的方式输出图片
            out = new FileOutputStream(imgFile);
            byte[] arr = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(arr)) != -1) {
                out.write(arr, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 回收资源
            close(client, response, inputStream, out);
        }
        return imgFile;
    }

    /**
     * 关闭资源
     *
     * @param closeables 资源列表
     **/
    private static void close(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 默认支持所有https
 */
class DefaultSSLUtils extends DefaultHttpClient {
    public DefaultSSLUtils() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

下载效果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值