HttpURLConnection进行简单的Tomcat下载

使用HttpURLConnection进行简单的网络下载,URL资源定位可以从网络上进行复制,openConnection打开网络链接,设置一些请求头,然后通过数据流的方式进行下载。话不多说,直接上代码,亲测可用。

public class httpConnection {

static URL url ;
static long fileSize;

public static void main(String []args){
    try {
        url = new URL("http://mirror.bit.edu.cn/apache/tomcat/tomcat-7/v7.0.90/bin/apache-tomcat-7.0.90.zip");
        HttpURLConnection connection = getConnection();
        if(connection.getResponseCode() == 200){
            System.out.println("200 Response");
            fileSize = connection.getContentLengthLong();
            System.out.println("200 Response size:"+fileSize);
            System.out.println("200 Response size:"+fileSize/1024/1024);
            System.out.println("200 Response size:"+connection.getHeaderField("Content-Disposition"));
            downloadFile(connection.getInputStream());
        }else {
            System.err.println("Not 200 Response"+connection.getResponseCode());
        }

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

public static void downloadFile(InputStream inputStream) throws IOException {
    DataInputStream dataInputStream = new DataInputStream(inputStream);
    File file = new File("C:\\Users\\Administrator\\Desktop\\tmp\\tmp.zip");
    if(!file.exists()){
        file.createNewFile();
    }
    FileOutputStream out = new FileOutputStream(file);

    byte []bytes = new byte[1024];
    int bit;
    while ((bit = dataInputStream.read(bytes))!= -1){
        out.write(bytes,0,bit);
    }
    out.flush();
    out.close();
    inputStream.close();
}

public static HttpURLConnection getConnection() throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(20000);
    connection.setReadTimeout(20000);
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setRequestProperty("contentType", "UTF-8");
    connection.setRequestMethod("GET");
    return connection;
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值