HttpURLConnection 下载

package com.downLoad;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * 单线程下载
 *
 */
public class DownLoad {

    public static final String path = "http://download.java.net/jdk/jdk-api-localizations/jdk-api-zh-cn/publish/1.6.0/chm/JDK_API_1_6_zh_CN.CHM";

    public static void main(String[] args) {
        // [一 ☆☆☆☆]获取服务器文件的大小 要计算每个线程下载的开始位置和结束位置
        try {
            // (1) 创建一个url对象 参数就是网址
            URL url = new URL(path);
            // (2)获取HttpURLConnection 链接对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // (3)设置参数 发送get请求
            conn.setRequestMethod("GET"); // 默认请求 就是get 要大写
            // (4)设置链接网络的超时时间
            conn.setConnectTimeout(5000);
            // (5)获取服务器返回的状态码
            int code = conn.getResponseCode(); // 200 代表获取服务器资源全部成功 206请求部分资源
            if (code == 200) {

                // (6)获取服务器文件的大小
                int length = conn.getContentLength();
                System.out.println("length:" + length);

                InputStream in = conn.getInputStream();
                File file = new File(getFilename(path));
                FileOutputStream out = new FileOutputStream(file);
                int len = -1;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                in.close();

                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取文件的名字
    private static String getFilename(String path) {
        int start = path.lastIndexOf("/") + 1;
        return path.substring(start);
    }
}
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值