java 从url下载图片或者网页

java 从url下载图片或者网页

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLDownloader extends Thread {

    private String url;
    private String filename;
    @Override
    public void run() {
        try {
            URL u = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) u.openConnection();
            //设置连接超时时间
            connection.setConnectTimeout(10000);
            //请求方式
            connection.setRequestMethod("GET");
            //从网络连接读取东西,默认是true,可以不设置
            connection.setDoInput(true);
            if (connection.getResponseCode() != 404){
                InputStream in = connection.getInputStream();
                File myfile = new File(filename);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(myfile));
                byte[] buff = new byte[1024];
                int read_size;
                while((read_size = in.read(buff))>0){
                    out.write(buff,0,read_size);
                }
                in.close();
                out.flush();
                out.close();
                connection.disconnect();
                System.out.println("下载成功 "+myfile.getName());
            }else {
                System.out.println("连接失败!请检查url是否有问题");
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public URLDownloader(String url,String filename) {
        super();
        this.url = url;
        this.filename = filename;
    }

    public static void main(String[] args) {
        new URLDownloader("https://thirdwx.qlogo.cn/mmopen/vi_32/aUtjLpqvmObCZS5J9T5j7HcwcoHqLqibXGsvvhZZ6qbgeu0ibHW5fn34iaTxhv9NtYaOblT8uoric4p3LSlHmngUbw/132","1.png").start();
        new URLDownloader("https://img2.baidu.com/it/u=1788336290,2322782865&fm=26&fmt=auto&gp=0.jpg","2.jpg").start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值